package com.qujia.station.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qujia.common.annotation.Log;
import com.qujia.common.constant.HttpStatus;
import com.qujia.common.constant.UserConstants;
import com.qujia.common.core.controller.BaseController;
import com.qujia.common.core.domain.AjaxResult;
import com.qujia.common.core.domain.entity.SysRole;
import com.qujia.common.core.domain.entity.SysUser;
import com.qujia.common.core.domain.model.LoginUser;
import com.qujia.common.core.page.TableDataInfo;
import com.qujia.common.core.redis.RedisCache;
import com.qujia.common.enums.BusinessType;
import com.qujia.common.enums.PayTypeEnum;
import com.qujia.common.enums.RechargeTypeEnum;
import com.qujia.common.exception.CustomException;
import com.qujia.common.utils.MathUtil;
import com.qujia.common.utils.SecurityUtils;
import com.qujia.common.utils.poi.ExcelUtil;
import com.qujia.customer.enums.CardRecordType;
import com.qujia.customer.service.ICustomerCardUseRecordService;
import com.qujia.station.domain.*;
import com.qujia.station.domain.dto.AutomaticClassDto;
import com.qujia.station.domain.dto.AutomaticClassInfo;
import com.qujia.station.domain.dto.CardClassSettDto;
import com.qujia.station.domain.dto.StationClassTimeDto;
import com.qujia.station.domain.vo.EnterpriseAndStationVo;
import com.qujia.station.domain.vo.StationClassTimeVo;
import com.qujia.station.domain.vo.changeClassSettlement4User;
import com.qujia.station.enums.PrintEnum;
import com.qujia.station.service.*;
import com.qujia.station.utils.FeiEPrinterUtil;
import com.qujia.station.utils.Methods;
import com.qujia.station.utils.StaffUtil;
import com.qujia.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.output.StringBuilderWriter;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 班结Controller
 *
 * @author qujia
 * @date 2021-11-27
 */
@RestController
@RequestMapping("/station/classSettlement")
@Api(tags = "班结相关接口", description = "班结相关接口")
@Slf4j
public class ClassSettlementController extends BaseController {
    @Autowired
    private IClassSettlementService classSettlementService;
    @Autowired
    private IStationService stationService;
    @Resource
    private IEnterpriseService enterpriseService;
    @Autowired
    private ClassSettlementCardService classSettlementCardService;
    @Autowired
    private IPayOrderService payOrderService;
    @Autowired
    private ICustomerCardUseRecordService customerCardUseRecordService;

    @Autowired
    private IStationDeviceManageService stationDeviceManageService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private AutomaticClassService automaticClassService;

    @Resource
    private ClassSettlementPrintService classSettlementPrintService;

    @Resource
    private ISysUserService sysUserService;

    /**
     * 查询未班结列表
     */
    @GetMapping("/initiateClassSe")
    public AjaxResult initiateClassSe(ClassSettlement classSettlement) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        LoginUser currentUser = SecurityUtils.getLoginUser();
        SysUser user = currentUser.getUser();
        Station station =  stationService.selectStationById(classSettlement.getStationId());
        String sign = sysUserService.getEmployeeSign(user.getUserId());
        // 员工权限
        if(user!=null && sign.equals("1")){


            if(station.getOpenStaffClass() == 1) {
                classSettlement.setOilPersonnelId(user.getUserId().toString());
                classSettlement.setOpenStaffClass(1);
            }else{
                return AjaxResult.error("当前未开启员工班结，请开启后再操作");

            }
        }else{

        }


        if (classSettlement.getStationId() == null) {
            return AjaxResult.error("参数不完整");
        }
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String startTime = null;
        Map<String, Object> params = new HashMap<String, Object>();
        Map<String, Object> paramsForOrder = new HashMap<String, Object>();
        params.put("stationId", classSettlement.getStationId());
        Station station1 = stationService.selectStationById(classSettlement.getStationId());
        params.put("oilPersonnelId", "0");

        if(station.getOpenStaffClass() == 1) {
            if( classSettlement.getOilPersonnelId()!=null){
                params.put("oilPersonnelId", classSettlement.getOilPersonnelId());
            }else{
                params.put("openStaffClassInStation", 1);
            }
        }
        Map<String, Object> endTimeMap = classSettlementService.queryLastEndTimeStaff(params);

        if (endTimeMap == null ){
            endTimeMap = classSettlementService.queryLastEndTime(params);
        }
        String currentTime = fmt.format(new Date());
        params.clear();
        params.put("serviceType", "POS");//pos机调用，group by只根据油品区分
        if (endTimeMap != null && endTimeMap.containsKey("classEndTime") && endTimeMap.get("classEndTime") != null) {
//            params.put("createStartTime","2021-07-10 00:00:00");
            startTime = endTimeMap.get("classEndTime").toString();
        }
        if(station.getOpenStaffClass() == 1) {
            if( classSettlement.getOilPersonnelId()!=null){
                params.put("oilPersonnelId", classSettlement.getOilPersonnelId());
            }else{
                params.put("openStaffClassInStation", 1);
            }
        }
        params.put("createStartTime", startTime);
        params.put("createEndTime", currentTime);
        params.put("stationId", classSettlement.getStationId());
        ClassSettlementCard superPay = classSettlementService.querySuperPay(params) ;

        if(Objects.nonNull(user) && StringUtils.isNotEmpty(user.getUserLevel())
                && UserConstants.LEVEL_THREE.equals(user.getUserLevel()) && Objects.nonNull(user.getUserId())){
            log.info("initiateClassSe userLevel():[{}],userId:[{}]",user.getUserLevel(),user.getUserId());
          
            // 员工权限
            if(user!=null && sign.equals("1")){
                params.put("oilPersonnelId",user.getUserId());
                log.info("员工权限下班结,oilPersonnelId:[{}]",user.getUserId());
                resultMap = employee(params,startTime,currentTime,classSettlement);
                return AjaxResult.success(resultMap);
            }
        }

        List<ClassSettlement> classSettlements = classSettlementService.queryUntreatedData(params);

        List<ClassSettlementCard> classSettlementCards = classSettlementCardService.queryUntreatedData(params);
        CardClassSettDto settDto = countCardSett(classSettlementCards); //电子卡交易汇总数据
      int openStaffClassInStation = 0;

        if(station.getOpenStaffClass() == 1) {
            if( classSettlement.getOilPersonnelId()!=null){

            }else{
                openStaffClassInStation = 1;
            }
        }else{
            openStaffClassInStation = 0;
        }
        paramsForOrder=   classSettlementService.getInfoForOrder(startTime,currentTime,classSettlement.getStationId(),settDto,openStaffClassInStation);

        params.put("serviceType", "BGS");
        List<ClassSettlement> classSettlements2 = classSettlementService.queryUntreatedData(params);
        // 调用方法获取总金额
        params.remove("serviceType");
//充值实付
        BigDecimal actualRechargeReceivedAmt =  classSettlementService.forActualRechargeReceivedAmt(settDto,params) ;

        ClassSettlementCard physicalCardRef = classSettlementService.queryPhysicalCardRef(params);

        BigDecimal killCouponAmt = classSettlementService.forKillCouponAmt(params) ;

        BigDecimal saleActivityAmt = classSettlementService.forSaleActivityAmt(params) ;

        BigDecimal saleActivityCom = classSettlementService.forSaleActivityCom(params) ;
//                优惠券核销，然后把核销的金额统计起来，放进优惠券金额汇总里面
        BigDecimal actualRechargeGiftAmt = settDto.getTotalGiveAmt();
        BigDecimal totalRechargeWithdrawalAmount = settDto.getTotalWithdrawalAmount();
        BigDecimal totalRechargeRefundAmt = settDto.getTotalRefundAmt().add(physicalCardRef.getAmt()!=null?physicalCardRef.getAmt():BigDecimal.ZERO);
        PayOrder payOrder = new PayOrder();
        payOrder.setStationId(classSettlement.getStationId());
        payOrder.setStartTime(startTime);
        payOrder.setStatus("1");
        payOrder.setEndTime(currentTime);
        //总支付渠道费
        BigDecimal result = BigDecimal.ZERO;
        Map<String, Object> summaryMap = new HashMap<String, Object>();
        Long orderCount = 0L;//订单笔数
        BigDecimal amt = BigDecimal.ZERO;//实收金额
        BigDecimal refundAmt = BigDecimal.ZERO;//退款金额
        BigDecimal consumptionRefundAmt = BigDecimal.ZERO;//消费合计退款
        BigDecimal receivableAmt = BigDecimal.ZERO;//应收金额
        BigDecimal returnCashAmt = BigDecimal.ZERO;//返利金的优惠
        BigDecimal giftReturnCash = BigDecimal.ZERO;//返利金
        BigDecimal bargainDiscountAmt = BigDecimal.ZERO;//议价优惠
        BigDecimal discountAmt = BigDecimal.ZERO;//优惠金额
        BigDecimal totalDiscountAmt = BigDecimal.ZERO;//优惠总金额
        BigDecimal allAmt = BigDecimal.ZERO;//到账总金额
        BigDecimal superPayAmt = superPay.getWithdrawalAmount();
        BigDecimal nodzkAmt = BigDecimal.ZERO;//无dzk实收总金额
        BigDecimal orderLiters = BigDecimal.ZERO;//加油升数
        BigDecimal moreAmt = BigDecimal.ZERO;//短款金额
        BigDecimal discountCouponAmt = BigDecimal.ZERO;//优惠券金额
        BigDecimal totalWithdrawalAmount = BigDecimal.ZERO;//到账总金额
        BigDecimal aggregatedPayment = BigDecimal.ZERO;//聚合支付
        BigDecimal presentAmount = BigDecimal.ZERO;//消费后赠送金额
        BigDecimal rechargeReduceDiscounts = BigDecimal.ZERO;//消费后赠送金额
        BigDecimal yhkCommission = BigDecimal.ZERO;//银行卡渠道费
        BigDecimal otherCommission = BigDecimal.ZERO;//非银行卡渠道费'wx', 'zfb', 'pos'

        for (ClassSettlement settlement : classSettlements) {
            orderCount = orderCount + settlement.getOrderCount();
            totalWithdrawalAmount = totalWithdrawalAmount.add(settlement.getTotalWithdrawalAmount());


            amt = amt.add(settlement.getAmt());
            nodzkAmt = nodzkAmt.add(settlement.getNodzkAmt());
            refundAmt = refundAmt.add(settlement.getRefundAmt());
            receivableAmt = receivableAmt.add(settlement.getReceivableAmt());
            if (settlement.getDiscountAmt() != null) {
                discountAmt = discountAmt.add(settlement.getDiscountAmt());
            }
            if (settlement.getPresentAmount() != null) {
                presentAmount = presentAmount.add(settlement.getPresentAmount());
            }
            if (settlement.getRechargeReduceDiscounts() != null) {
                rechargeReduceDiscounts = rechargeReduceDiscounts.add(settlement.getRechargeReduceDiscounts());
            }
            if (settlement.getOrderLiters() != null) {
                orderLiters = orderLiters.add(settlement.getOrderLiters());
            }
            moreAmt = moreAmt.add(settlement.getMoreAmt());
            if (settlement.getDiscountCouponAmt() != null) {
                discountCouponAmt = discountCouponAmt.add(settlement.getDiscountCouponAmt());
            }

            if (settlement.getReturnCashAmt() != null) {
                returnCashAmt = returnCashAmt.add(settlement.getReturnCashAmt());
            }
            if (settlement.getGiftReturnCash() != null) {
                giftReturnCash = giftReturnCash.add(settlement.getGiftReturnCash());
            }
            if (settlement.getBargainDiscountAmt() != null) {
                bargainDiscountAmt = bargainDiscountAmt.add(settlement.getBargainDiscountAmt());
            }

        }

        otherCommission= otherCommission.add(settDto.getTotalServiceCharge()!= null ? settDto.getTotalServiceCharge() : BigDecimal.ZERO)
                .add(superPay.getServiceCharge()!= null ?superPay.getServiceCharge():BigDecimal.ZERO).add(saleActivityCom);
//        这里是消费的到账赋值给聚合支付   现在加上秒杀的订单saleActivityAmt
        totalWithdrawalAmount =  totalWithdrawalAmount.add(saleActivityAmt);
        aggregatedPayment = totalWithdrawalAmount;
        consumptionRefundAmt = refundAmt;
//        加上电子卡退款数据
        refundAmt=  refundAmt.add(totalRechargeRefundAmt != null ? totalRechargeRefundAmt : BigDecimal.ZERO);
        for(ClassSettlement settlement :classSettlements2){
            if (result != null && settlement != null && settlement.getCommission() != null) {
                result = result.add(settlement.getCommission());
            }
            if(settlement.getPayType().equals("yhk")){
                yhkCommission= yhkCommission.add(settlement.getCommission() != null ? settlement.getCommission() : BigDecimal.ZERO);
            }else if(settlement.getPayType().equals("wx")||settlement.getPayType().equals("zfb")||settlement.getPayType().equals("pos")){
                otherCommission=  otherCommission.add(settlement.getCommission() != null ? settlement.getCommission() : BigDecimal.ZERO);
            }
        }
             totalWithdrawalAmount = totalWithdrawalAmount.add(totalRechargeWithdrawalAmount != null ? totalRechargeWithdrawalAmount : BigDecimal.ZERO).add(superPayAmt != null ? superPayAmt : BigDecimal.ZERO);
            summaryMap.put("totalWithdrawalAmount", totalWithdrawalAmount.setScale(2, RoundingMode.DOWN));


        if (result != null) {
            summaryMap.put("commission", result.setScale(2, RoundingMode.UP));
        } else {
            summaryMap.put("commission", BigDecimal.ZERO);
        }

//        从电子卡汇总里取出微信充值，手动增加,再取出车队卡和实体卡
        List<ClassSettlementCard> transactionSummary = classSettlementService.getTransactionSummary(settDto, params);
        //        取出退款汇总
        List<ClassSettlement> refundSummary = classSettlementService.getRefundSummary(settDto, params);


        List<CouponSummary> couponSummary = classSettlementService.queryCouponSum(params);
        CouponSummary CouponSummaryAll = new CouponSummary();
        CouponSummaryAll.setCouponType("合计");
        CouponSummaryAll.setCouponAmt(BigDecimal.ZERO);
        CouponSummaryAll.setCount(0);
        for(CouponSummary coupon :couponSummary){
            CouponSummaryAll.setCount(CouponSummaryAll.getCount()+coupon.getCount());
            CouponSummaryAll.setCouponAmt(CouponSummaryAll.getCouponAmt().add(coupon.getCouponAmt()));
        }
        couponSummary.add(CouponSummaryAll);

        totalDiscountAmt = discountAmt.add(discountCouponAmt).add(bargainDiscountAmt);
        allAmt =  nodzkAmt.add(actualRechargeReceivedAmt != null ? actualRechargeReceivedAmt : BigDecimal.ZERO);
        //充值赠送合计金额
        summaryMap.put("totalPresentAmt", Objects.isNull(actualRechargeGiftAmt) ? BigDecimal.ZERO : actualRechargeGiftAmt);
        summaryMap.put("orderCount", orderCount);
        summaryMap.put("presentAmount", presentAmount);
        summaryMap.put("rechargeReduceDiscounts", rechargeReduceDiscounts);
        summaryMap.put("yhkCommission", yhkCommission.setScale(2, RoundingMode.HALF_UP));
        summaryMap.put("otherCommission", otherCommission.setScale(2, RoundingMode.HALF_UP));
        summaryMap.put("allCommission", otherCommission.add(yhkCommission).setScale(2, RoundingMode.HALF_UP));
        summaryMap.put("isShowCommission", station1.getIsShowCommission());
        summaryMap.put("transactionSummary", transactionSummary);
        summaryMap.put("couponSummary", couponSummary);
        summaryMap.put("refundSummary", refundSummary);
        summaryMap.put("amt", amt);
        summaryMap.put("refundAmt", refundAmt);
        summaryMap.put("receivableAmt", receivableAmt);
        summaryMap.put("giftReturnCash", giftReturnCash);
        summaryMap.put("returnCashAmt", returnCashAmt);
        summaryMap.put("discountAmt", discountAmt);
        summaryMap.put("killCouponAmt", killCouponAmt);
        summaryMap.put("orderLiters", orderLiters);
        summaryMap.put("moreAmt", moreAmt);
        summaryMap.put("discountCouponAmt", discountCouponAmt);
        //        消费合计退款
        summaryMap.put("consumptionRefundAmt", consumptionRefundAmt);
//        优惠金额
        summaryMap.put("totalDiscountAmt", totalDiscountAmt);
//        充值合计提现
        summaryMap.put("totalRechargeWithdrawalAmount", totalRechargeWithdrawalAmount);
        totalRechargeRefundAmt.add(physicalCardRef.getAmt() != null?physicalCardRef.getAmt():BigDecimal.ZERO);
//        充值合计退款
        summaryMap.put("totalRechargeRefundAmt", totalRechargeRefundAmt);
//        到账总金额
        summaryMap.put("allAmt", allAmt);
        //        聚合支付总金额=订单数据提现金额
        summaryMap.put("aggregatedPayment", aggregatedPayment);
        summaryMap.put("saleActivityAmt", saleActivityAmt);
        summaryMap.put("actualRechargeReceivedAmt", actualRechargeReceivedAmt);
        resultMap.put("summary", summaryMap);
        resultMap.put("details", classSettlements); //班结明细
        resultMap.put("classSettlementCardsSum", classSettlementCards); // 电子卡明细
        resultMap.put("cardSum", settDto);

        resultMap.put("createEndTime", currentTime);
        if (startTime != null) {
            // 保留年月日时分秒部分，截取前19个字符
            String formattedEndTime = startTime.substring(0, 19);
            resultMap.put("startTime", formattedEndTime);
        }else{
            resultMap.put("startTime", startTime);
        }
        //增加充值和开通超级会员的记录
        // 非空判断，将paramsForOrder合并到resultMap
        if (paramsForOrder != null) {
            resultMap.putAll(paramsForOrder);  //直接查看详情
        }

        return AjaxResult.success(resultMap);
    }

    // 员工账号看班结
    private Map<String, Object> employee(Map<String, Object> params, String startTime, String currentTime, ClassSettlement classSettlement){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> paramsForOrder = new HashMap<String, Object>();
        List<ClassSettlement> classSettlements = classSettlementService.employeeQueryUntreatedData(params);
        // 优惠券核销金额
        BigDecimal killCouponAmt = classSettlementService.employeeForKillCouponAmt(params);

        List<ClassSettlementCard> classSettlementCards = classSettlementCardService.queryUntreatedData(params);
        CardClassSettDto settDto = countCardSett(classSettlementCards); //电子卡交易汇总数据
          // 取出退款汇总
        List<ClassSettlement> refundSummary = classSettlementService.employeeGetRefundSummary(params);
//        paramsForOrder=   classSettlementService.getInfoForOrder(startTime,currentTime,classSettlement.getStationId(),settDto);
        //员工权限下查询班结详情
        paramsForOrder=   classSettlementService.getEmployeeInfoForOrder(startTime,currentTime,params.get("oilPersonnelId").toString(),params);
        Map<String, Object> summaryMap = new HashMap<String, Object>();

        Long orderCount = 0L;//订单笔数
        BigDecimal amt = BigDecimal.ZERO;//消费合计应收
        BigDecimal refundAmt = BigDecimal.ZERO;//退款合计金额
        BigDecimal consumptionRefundAmt = BigDecimal.ZERO;//消费合计退款
        BigDecimal receivableAmt = BigDecimal.ZERO;//消费合计应收
        BigDecimal discountAmt = BigDecimal.ZERO;// 立减合计金额
        BigDecimal totalDiscountAmt = BigDecimal.ZERO;//消费合计优惠
        BigDecimal allAmt = BigDecimal.ZERO;//到账总金额
        BigDecimal nodzkAmt = BigDecimal.ZERO;//无dzk实收总金额
        BigDecimal orderLiters = BigDecimal.ZERO;//加油升数
        BigDecimal moreAmt = BigDecimal.ZERO;//短款金额
        BigDecimal discountCouponAmt = BigDecimal.ZERO;//优惠券合计金额
        BigDecimal totalWithdrawalAmount = BigDecimal.ZERO;//提现金额
        BigDecimal aggregatedPayment = BigDecimal.ZERO;//聚合支付
        BigDecimal presentAmount = BigDecimal.ZERO;//消费后赠送金额
        BigDecimal rechargeReduceDiscounts = BigDecimal.ZERO;//消费后赠送金额

        for (ClassSettlement settlement : classSettlements) {
            orderCount = orderCount + settlement.getOrderCount();
            totalWithdrawalAmount = totalWithdrawalAmount.add(settlement.getTotalWithdrawalAmount());

            amt = amt.add(settlement.getAmt());
            nodzkAmt = nodzkAmt.add(settlement.getNodzkAmt());
            refundAmt = refundAmt.add(settlement.getRefundAmt());
            receivableAmt = receivableAmt.add(settlement.getReceivableAmt()); // 消费合计应收
            if (settlement.getDiscountAmt() != null) {
                discountAmt = discountAmt.add(settlement.getDiscountAmt());
            }
            if (settlement.getPresentAmount() != null) {
                presentAmount = presentAmount.add(settlement.getPresentAmount());
            }
            if (settlement.getRechargeReduceDiscounts() != null) {
                rechargeReduceDiscounts = rechargeReduceDiscounts.add(settlement.getRechargeReduceDiscounts());
            }
            if (settlement.getOrderLiters() != null) {
                orderLiters = orderLiters.add(settlement.getOrderLiters());
            }
            moreAmt = moreAmt.add(settlement.getMoreAmt());
            if (settlement.getDiscountCouponAmt() != null) {
                discountCouponAmt = discountCouponAmt.add(settlement.getDiscountCouponAmt());
            }

        }
//        从电子卡汇总里取出微信充值，手动增加,再取出车队卡和实体卡
        List<ClassSettlementCard> transactionSummary = classSettlementService.getStaffTransactionSummary(settDto, params);
        allAmt = totalWithdrawalAmount;
        aggregatedPayment = totalWithdrawalAmount;
        consumptionRefundAmt = refundAmt;
        BigDecimal actualRechargeReceivedAmt =  settDto.getAllAmt();
        BigDecimal actualRechargeGiftAmt =  settDto.getTotalGiveAmt();
        BigDecimal totalRechargeRefundAmt = settDto.getTotalRefundAmt();

        //充值合计赠送 不要
        summaryMap.put("totalPresentAmt", Objects.isNull(actualRechargeGiftAmt) ? BigDecimal.ZERO : actualRechargeGiftAmt);

        summaryMap.put("orderCount", orderCount);  // 订单数量 要
        summaryMap.put("presentAmount", presentAmount); // 消费赠送总金额 要
        summaryMap.put("rechargeReduceDiscounts", rechargeReduceDiscounts); // 充值立减优惠 不要
        summaryMap.put("transactionSummary", transactionSummary);
        summaryMap.put("refundSummary", refundSummary); // PC端 退款-汇总 要
        summaryMap.put("amt", amt);  // 消费合计应收 要
        summaryMap.put("refundAmt", refundAmt);  // 退款合计金额(电子卡退款没有区分员工和油站，不取) 要
        summaryMap.put("receivableAmt", receivableAmt);  //消费合计应收 要
        summaryMap.put("discountAmt", discountAmt);  //  立减合计金额 要
        summaryMap.put("killCouponAmt", killCouponAmt); // 优惠券核销金额 要
        summaryMap.put("orderLiters", orderLiters); // 加油升数 可以留
        summaryMap.put("moreAmt", moreAmt); // 长短款 可以留
        summaryMap.put("discountCouponAmt", discountCouponAmt);  // 优惠券合计金额 要

        summaryMap.put("consumptionRefundAmt", consumptionRefundAmt); // 消费合计退款 要
        summaryMap.put("totalDiscountAmt", totalDiscountAmt); // 消费合计优惠 要
        summaryMap.put("totalRechargeWithdrawalAmount", BigDecimal.ZERO);  //充值合计提现 不要
        summaryMap.put("totalRechargeRefundAmt", totalRechargeRefundAmt);// 充值合计退款 不要
        summaryMap.put("allAmt", allAmt);  // 到账总金额 要 更换字段
        //        聚合支付总金额=订单数据提现金额
        summaryMap.put("aggregatedPayment", aggregatedPayment); // 聚合支付消费合计 要
        summaryMap.put("actualRechargeReceivedAmt", actualRechargeReceivedAmt);// 充值实收合计 不要
        summaryMap.put("totalWithdrawalAmount", totalWithdrawalAmount); // 提现总金额 ; 到账总金额 更换字段

        resultMap.put("summary", summaryMap); // 班结对账汇总
        resultMap.put("details", classSettlements); //班结明细 可以留
        resultMap.put("classSettlementCardsSum", null); // 电子卡明细 不要
        resultMap.put("cardSum", null); // 对应PC端 电子卡-交易汇总 不要

        resultMap.put("createEndTime", currentTime);
        if (startTime != null) {
            // 保留年月日时分秒部分，截取前19个字符
            String formattedEndTime = startTime.substring(0, 19);
            resultMap.put("startTime", formattedEndTime);
        }else{
            resultMap.put("startTime", startTime);
        }
        // 非空判断，将paramsForOrder合并到resultMap
        if (paramsForOrder != null) {
            resultMap.putAll(paramsForOrder);  //直接查看详情
        }

        return resultMap;
    }

    /**
     * 班级批量删除
     *
     * @param classNo 班结结算ID数组
     * @return AjaxResult
     */
    @ApiOperation("班结批量删除")
    @DeleteMapping("/delete")
    public AjaxResult delete(@RequestBody String[] classNo) {
        int i = classSettlementService.deleteClassSettlementByClassNos(classNo);
        if (i <= 0) {
            return AjaxResult.error();
        }
        return AjaxResult.success();
    }

    /**
     * 获取创建人列表
     */
    @GetMapping(value = "/createList")
    @ApiOperation("获取创建人列表")
    public List<Map<String, Object>> createList() {
        ClassSettlement  classSettlement = new ClassSettlement();
        LoginUser currentUser = SecurityUtils.getLoginUser();
        SysUser user = currentUser.getUser();
        if (user.getUserLevel() == null) {
            //   classSettlement.setEnterpriseId(user.getEnterpriseId());
        } else if (user.getUserLevel() != null && user.getUserLevel().equals("1")) {
            classSettlement.setEnterpriseId(user.getEnterpriseId());
        } else if (user.getUserLevel().equals("2")) {
            String sign = sysUserService.getEmployeeSign(user.getUserId());
            // 员工权限
            if(user!=null && sign.equals("1")){
                List<Map<String, Object>>  createList = new ArrayList<>();
                return  createList;
            }
            classSettlement.setStationId(user.getStationId());
        }
        return  classSettlementService.createList(classSettlement);
    }

    /**
     * 查询班结列表
     */
    @GetMapping("/list")
    @ApiOperation("班结列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "beginTime", value = "开始时间", dataType = "String", paramType = "query", example = "2023-05-25 10:00:00"),
            @ApiImplicitParam(name = "endTime", value = "截止时间", dataType = "String", paramType = "query", example = "2023-05-25 18:00:00"),
            @ApiImplicitParam(name = "enterpriseId", value = "企业ID", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "stationId", value = "油站ID", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "classNo", value = "班结ID", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "classesDayOrNight", value = "班次", dataType = "String", paramType = "query")
    })
    public TableDataInfo list(ClassSettlement classSettlement) {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        SysUser user = currentUser.getUser();
        if (classSettlement.getBeginTime() != "" && classSettlement.getEndTime() != "") {
            // 将字符串转换为LocalDate类型
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDate beginDate = LocalDate.parse(classSettlement.getBeginTime(), formatter);
            LocalDate endDate = LocalDate.parse(classSettlement.getEndTime(), formatter);

            // 计算两个日期之间的差值
            long daysBetween = ChronoUnit.DAYS.between(beginDate, endDate);

            // 如果差值超过一个月，返回失败
            if (daysBetween > 31) {
                List<ClassSettlement> betweenTime = new ArrayList<>();
                TableDataInfo rspData = new TableDataInfo();
                rspData.setCode(HttpStatus.ERROR);
                rspData.setMsg("仅可查询一个月");
                rspData.setRows(betweenTime);
                rspData.setTotal((long) 0);
                return rspData;
            }
        } else {
            if (!com.qujia.common.utils.StringUtils.equals(UserConstants.LEVEL_THREE, user.getUserLevel())) {
                // 开始时间和结束时间为空的逻辑
                LocalDate today = LocalDate.now(); // 当前日期
                LocalDate sevenDaysAgo = today.minusDays(7); // 当前日期往前7天的日期

                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); // 定义日期时间格式化模式

                LocalDateTime beginTime = LocalDateTime.of(sevenDaysAgo, LocalTime.MIN); // 开始时间为当天的最早时间（00:00:00）
                LocalDateTime endTime = LocalDateTime.of(today, LocalTime.MAX); // 结束时间为当天的最晚时间（23:59:59）

                String beginTimeStr = beginTime.format(formatter); // 格式化开始时间为字符串
                String endTimeStr = endTime.format(formatter); // 格式化结束时间为字符串

// 将开始时间和结束时间的字符串赋值给相应的变量
                classSettlement.setBeginTime(beginTimeStr);
                classSettlement.setEndTime(endTimeStr);
            }
        }


        if (user.getUserLevel() == null) {
         //   classSettlement.setEnterpriseId(user.getEnterpriseId());
        } else if (user.getUserLevel() != null && user.getUserLevel().equals("1")) {
            classSettlement.setEnterpriseId(user.getEnterpriseId());
            classSettlement.setOpenStaffClass(1);
        } else if (user.getUserLevel().equals("2")) {
            classSettlement.setStationId(user.getStationId());
            classSettlement=   payOrderService.classSettlementtimeSetting(classSettlement,currentUser.getUser().getStationId());

            Station station1 = stationService.selectStationById(classSettlement.getStationId());
            classSettlement.setOpenStaffClass(station1.getOpenStaffClass());
        }else if(SecurityUtils.isPartner()){
            EnterpriseAndStationVo itemIds = stationService.getItemIds(currentUser.getUser());
            List<Long> enterpriseIds = itemIds.getEnterpriseIds();
            if (enterpriseIds != null && enterpriseIds.size()>0) {
                classSettlement.setEnterpriseIdListForAuthor(enterpriseIds);
            } else {
                throw new CustomException(UserConstants.NO_ENTERPRISE);
            }
        }
        List<ClassSettlement> list = new ArrayList<>();
        String sign = sysUserService.getEmployeeSign(user.getUserId());
        // 员工权限
        if(user!=null && sign.equals("1")){

            classSettlement.setCreateUser(user.getUserId());
            startPage();
            list= classSettlementService.selectClassSettlementStaffSummaryList(classSettlement);
        }else{
            startPage();
            list= classSettlementService.selectClassSettlementSummaryList(classSettlement);
        }

        return getDataTable(list);
    }

    /**
     * 查询班结列表
     */
    @GetMapping("/classTimeList")
    @ApiOperation("班结时间下拉框")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "beginTime", value = "开始时间", dataType = "String", paramType = "query", example = "2023-05-25 10:00:00"),
            @ApiImplicitParam(name = "endTime", value = "截止时间", dataType = "String", paramType = "query", example = "2023-05-25 18:00:00"),
            @ApiImplicitParam(name = "enterpriseId", value = "企业ID", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "stationId", value = "油站ID", dataType = "Long", paramType = "query")
    })
    public TableDataInfo classTimeList(ClassSettlement classSettlement) {
            // 开始时间和结束时间为空的逻辑
        if (classSettlement.getBeginTime() != null && classSettlement.getEndTime() != null) {
        } else {
            // 开始时间和结束时间为空的逻辑
            LocalDate todayaa = LocalDate.now(); // 当前日期
            LocalDate today = todayaa.minusDays(-1);
            LocalDate sevenDaysAgo = todayaa.minusDays(7); // 当前日期往前7天的日期

            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); // 定义日期时间格式化模式

            LocalDateTime beginTime = LocalDateTime.of(sevenDaysAgo, LocalTime.MIN); // 开始时间为当天的最早时间（00:00:00）
            LocalDateTime endTime = LocalDateTime.of(today, LocalTime.MAX); // 结束时间为当天的最晚时间（23:59:59）

            String beginTimeStr = beginTime.format(formatter); // 格式化开始时间为字符串
            String endTimeStr = endTime.format(formatter); // 格式化结束时间为字符串

// 将开始时间和结束时间的字符串赋值给相应的变量
            classSettlement.setBeginTime(beginTimeStr);
            classSettlement.setEndTime(endTimeStr);
        }
        LoginUser currentUser = SecurityUtils.getLoginUser();
        SysUser user = currentUser.getUser();
        startPage();
        if (user.getUserLevel() == null) {
            //   classSettlement.setEnterpriseId(user.getEnterpriseId());
        } else if (user.getUserLevel() != null && user.getUserLevel().equals("1")) {
            classSettlement.setEnterpriseId(user.getEnterpriseId());
        } else if (user.getUserLevel().equals("2")) {
            classSettlement.setStationId(user.getStationId());
        }else if(SecurityUtils.isPartner()){
            EnterpriseAndStationVo itemIds = stationService.getItemIds(currentUser.getUser());
            List<Long> enterpriseIds = itemIds.getEnterpriseIds();
            if (enterpriseIds != null && enterpriseIds.size()>0) {
                classSettlement.setEnterpriseIdListForAuthor(enterpriseIds);
            } else {
                throw new CustomException(UserConstants.NO_ENTERPRISE);
            }
        }

        List<ClassSettlement> list = classSettlementService.classTimeList(classSettlement);
        return getDataTable(list);
    }


    @GetMapping("/selectBusinessDailyReportList")
    @ApiOperation("日经营列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "beginTime", value = "开始时间", dataType = "String", paramType = "query", example = "2023-05-25 10:00:00"),
            @ApiImplicitParam(name = "endTime", value = "截止时间", dataType = "String", paramType = "query", example = "2023-05-25 18:00:00"),
            @ApiImplicitParam(name = "enterpriseId", value = "企业ID", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "stationId", value = "油站ID", dataType = "Long", paramType = "query")

    })
    public TableDataInfo selectBusinessDailyReportList(ClassSettlement classSettlement) {
        if (classSettlement.getBeginTime() != null && !classSettlement.getBeginTime().isEmpty()
                && classSettlement.getEndTime() != null && !classSettlement.getEndTime().isEmpty()){
            // 将字符串转换为LocalDate类型
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate beginDate = LocalDate.parse(classSettlement.getBeginTime(), formatter);
            LocalDate endDate = LocalDate.parse(classSettlement.getEndTime(), formatter);

            // 计算两个日期之间的差值
            long daysBetween = ChronoUnit.DAYS.between(beginDate, endDate);

            // 如果差值超过一个月，返回失败
            if (daysBetween > 31) {
                List<ClassSettlement> betweenTime = new ArrayList<>();
                TableDataInfo rspData = new TableDataInfo();
                rspData.setCode(HttpStatus.ERROR);
                rspData.setMsg("查询时间不能大于一个月");
                rspData.setRows(betweenTime);
                rspData.setTotal((long) 0);
                return rspData;
            }
        } else {
            // 开始时间和结束时间为空的逻辑
            LocalDate todayaa = LocalDate.now(); // 当前日期
            LocalDate today = todayaa.minusDays(-1);
            LocalDate sevenDaysAgo = todayaa.minusDays(7); // 当前日期往前7天的日期

            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); // 定义日期时间格式化模式

            LocalDateTime beginTime = LocalDateTime.of(sevenDaysAgo, LocalTime.MIN); // 开始时间为当天的最早时间（00:00:00）
            LocalDateTime endTime = LocalDateTime.of(today, LocalTime.MAX); // 结束时间为当天的最晚时间（23:59:59）

            String beginTimeStr = beginTime.format(formatter); // 格式化开始时间为字符串
            String endTimeStr = endTime.format(formatter); // 格式化结束时间为字符串

// 将开始时间和结束时间的字符串赋值给相应的变量
            classSettlement.setBeginTime(beginTimeStr);
            classSettlement.setEndTime(endTimeStr);
        }
        LoginUser currentUser = SecurityUtils.getLoginUser();
        SysUser user = currentUser.getUser();
        startPage();
        if (user.getUserLevel() == null) {
            //   classSettlement.setEnterpriseId(user.getEnterpriseId());
        } else if (user.getUserLevel() != null && user.getUserLevel().equals("1")) {
            classSettlement.setEnterpriseId(user.getEnterpriseId());
        } else if (user.getUserLevel().equals("2")) {
            classSettlement.setStationId(user.getStationId());
        }else if(SecurityUtils.isPartner()){
            EnterpriseAndStationVo itemIds = stationService.getItemIds(currentUser.getUser());
            List<Long> enterpriseIds = itemIds.getEnterpriseIds();
            if (enterpriseIds != null && enterpriseIds.size()>0) {
                classSettlement.setEnterpriseIdListForAuthor(enterpriseIds);
            } else {
                throw new CustomException(UserConstants.NO_ENTERPRISE);
            }
        }
if(classSettlement.getClassNoList()!=null&&classSettlement.getClassNoList().size() > 0){
    List<BusinessDailyReport> list = classSettlementService.selectClassSettlementSummaryListInReport(classSettlement);
    return getDataTable(list);
}else{
    List<BusinessDailyReport> list = classSettlementService.selectBusinessDailyReportList(classSettlement);
    return getDataTable(list);
}


    }

    @GetMapping("/exportBusinessDailyReportList")
    @ApiOperation("日经营列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "beginTime", value = "开始时间", dataType = "String", paramType = "query", example = "2023-05-25 10:00:00"),
            @ApiImplicitParam(name = "endTime", value = "截止时间", dataType = "String", paramType = "query", example = "2023-05-25 18:00:00"),
            @ApiImplicitParam(name = "enterpriseId", value = "企业ID", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "stationId", value = "油站ID", dataType = "Long", paramType = "query")

    })
    public AjaxResult exportBusinessDailyReportList(ClassSettlement classSettlement) {
        if (classSettlement.getBeginTime() != null && !classSettlement.getBeginTime().isEmpty()
                && classSettlement.getEndTime() != null && !classSettlement.getEndTime().isEmpty()){
            // 将字符串转换为LocalDate类型
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate beginDate = LocalDate.parse(classSettlement.getBeginTime(), formatter);
            LocalDate endDate = LocalDate.parse(classSettlement.getEndTime(), formatter);

            // 计算两个日期之间的差值
            long daysBetween = ChronoUnit.DAYS.between(beginDate, endDate);

            // 如果差值超过一个月，返回失败
            if (daysBetween > 31) {
                return AjaxResult.error("仅可查询一个月");
            }
        } else {
            // 开始时间和结束时间为空的逻辑
            LocalDate todayaa = LocalDate.now(); // 当前日期
            LocalDate today = todayaa.minusDays(-1);
            LocalDate sevenDaysAgo = todayaa.minusDays(7); // 当前日期往前7天的日期

            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); // 定义日期时间格式化模式

            LocalDateTime beginTime = LocalDateTime.of(sevenDaysAgo, LocalTime.MIN); // 开始时间为当天的最早时间（00:00:00）
            LocalDateTime endTime = LocalDateTime.of(today, LocalTime.MAX); // 结束时间为当天的最晚时间（23:59:59）

            String beginTimeStr = beginTime.format(formatter); // 格式化开始时间为字符串
            String endTimeStr = endTime.format(formatter); // 格式化结束时间为字符串

// 将开始时间和结束时间的字符串赋值给相应的变量
            classSettlement.setBeginTime(beginTimeStr);
            classSettlement.setEndTime(endTimeStr);
        }
        LoginUser currentUser = SecurityUtils.getLoginUser();
        SysUser user = currentUser.getUser();

        if (user.getUserLevel() == null) {
            //   classSettlement.setEnterpriseId(user.getEnterpriseId());
        } else if (user.getUserLevel() != null && user.getUserLevel().equals("1")) {
            classSettlement.setEnterpriseId(user.getEnterpriseId());
        } else if (user.getUserLevel().equals("2")) {
            classSettlement.setStationId(user.getStationId());
        }else if(SecurityUtils.isPartner()){
            EnterpriseAndStationVo itemIds = stationService.getItemIds(currentUser.getUser());
            List<Long> enterpriseIds = itemIds.getEnterpriseIds();
            if (enterpriseIds != null && enterpriseIds.size()>0) {
                classSettlement.setEnterpriseIdListForAuthor(enterpriseIds);
            } else {
                throw new CustomException(UserConstants.NO_ENTERPRISE);
            }
        }

        if(classSettlement.getClassNoList()!=null&&classSettlement.getClassNoList().size() > 0){

            List<BusinessDailyReport> list = classSettlementService.selectClassSettlementSummaryListInReport(classSettlement);

            ExcelUtil<BusinessDailyReport> util = new ExcelUtil<BusinessDailyReport>(BusinessDailyReport.class);
            return util.exportExcel(list, "businessDailyReport");
        }else{
            List<BusinessDailyReport> list = classSettlementService.selectBusinessDailyReportList(classSettlement);

            ExcelUtil<BusinessDailyReport> util = new ExcelUtil<BusinessDailyReport>(BusinessDailyReport.class);
            return util.exportExcel(list, "businessDailyReport");
        }


    }


    @GetMapping("/selectBusinessDailyReportSum")
    @ApiOperation("日经营列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "beginTime", value = "开始时间", dataType = "String", paramType = "query", example = "2023-05-25 10:00:00"),
            @ApiImplicitParam(name = "endTime", value = "截止时间", dataType = "String", paramType = "query", example = "2023-05-25 18:00:00"),
            @ApiImplicitParam(name = "enterpriseId", value = "企业ID", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "stationId", value = "油站ID", dataType = "Long", paramType = "query")

    })
    public AjaxResult selectBusinessDailyReportSum(ClassSettlement classSettlement) {
        if (classSettlement.getBeginTime() != null && !classSettlement.getBeginTime().isEmpty()
                && classSettlement.getEndTime() != null && !classSettlement.getEndTime().isEmpty()){
            // 将字符串转换为LocalDate类型
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate beginDate = LocalDate.parse(classSettlement.getBeginTime(), formatter);
            LocalDate endDate = LocalDate.parse(classSettlement.getEndTime(), formatter);

            // 计算两个日期之间的差值
            long daysBetween = ChronoUnit.DAYS.between(beginDate, endDate);

            // 如果差值超过一个月，返回失败
            if (daysBetween > 31) {

                return AjaxResult.error("查询时间不能大于一个月");
            }
        } else {
            // 开始时间和结束时间为空的逻辑
            LocalDate todayaa = LocalDate.now(); // 当前日期
            LocalDate today = todayaa.minusDays(-1);
            LocalDate sevenDaysAgo = todayaa.minusDays(7); // 当前日期往前7天的日期

            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); // 定义日期时间格式化模式

            LocalDateTime beginTime = LocalDateTime.of(sevenDaysAgo, LocalTime.MIN); // 开始时间为当天的最早时间（00:00:00）
            LocalDateTime endTime = LocalDateTime.of(today, LocalTime.MAX); // 结束时间为当天的最晚时间（23:59:59）

            String beginTimeStr = beginTime.format(formatter); // 格式化开始时间为字符串
            String endTimeStr = endTime.format(formatter); // 格式化结束时间为字符串

// 将开始时间和结束时间的字符串赋值给相应的变量
            classSettlement.setBeginTime(beginTimeStr);
            classSettlement.setEndTime(endTimeStr);
        }
        LoginUser currentUser = SecurityUtils.getLoginUser();
        SysUser user = currentUser.getUser();

        if (user.getUserLevel() == null) {
            //   classSettlement.setEnterpriseId(user.getEnterpriseId());
        } else if (user.getUserLevel() != null && user.getUserLevel().equals("1")) {
            classSettlement.setEnterpriseId(user.getEnterpriseId());
        } else if (user.getUserLevel().equals("2")) {
            classSettlement.setStationId(user.getStationId());
        }else if(SecurityUtils.isPartner()){
            EnterpriseAndStationVo itemIds = stationService.getItemIds(currentUser.getUser());
            List<Long> enterpriseIds = itemIds.getEnterpriseIds();
            if (enterpriseIds != null && enterpriseIds.size()>0) {
                classSettlement.setEnterpriseIdListForAuthor(enterpriseIds);
            } else {
                throw new CustomException(UserConstants.NO_ENTERPRISE);
            }
        }
        if(classSettlement.getClassNoList()!=null&&classSettlement.getClassNoList().size() > 0){

            return  AjaxResult.success(classSettlementService.selectBusinessDailyReportSumInReport(classSettlement));
        }else{
            return  AjaxResult.success(classSettlementService.selectBusinessDailyReportSum(classSettlement));
        }


    }





    @Log(title = "日报表导出", businessType = BusinessType.EXPORT)
    @ApiOperation("日报表导出")
    @GetMapping("/exportClassReport")
    public AjaxResult exportClassReport(ClassSettlement classSettlement) {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        SysUser user = currentUser.getUser();
        if (user.getUserLevel() != null) {
            if (user.getUserLevel().equals("1")) {
                classSettlement.setEnterpriseId(user.getEnterpriseId());
            } else if (user.getUserLevel().equals("2")) {
                classSettlement.setStationId(user.getStationId());
            }else if(SecurityUtils.isPartner()){
                EnterpriseAndStationVo itemIds = stationService.getItemIds(currentUser.getUser());
                List<Long> enterpriseIds = itemIds.getEnterpriseIds();
                if (enterpriseIds != null && enterpriseIds.size()>0) {
                    classSettlement.setEnterpriseIdListForAuthor(enterpriseIds);
                } else {
                    throw new CustomException(UserConstants.NO_ENTERPRISE);
                }
            }
        }
        List<ReportSettlement> list = classSettlementService.selectReportClassList(classSettlement);

        ExcelUtil<ReportSettlement> util = new ExcelUtil<ReportSettlement>(ReportSettlement.class);
        return util.exportExcel(list, "reportSettlement");
    }
    /**
     * 查询班结列表
     */
    @GetMapping("/classReportList")
    @ApiOperation("日报表列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "beginTime", value = "开始时间", dataType = "String", paramType = "query", example = "2023-05-25 10:00:00"),
            @ApiImplicitParam(name = "endTime", value = "截止时间", dataType = "String", paramType = "query", example = "2023-05-25 18:00:00"),
            @ApiImplicitParam(name = "enterpriseId", value = "企业ID", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "stationId", value = "油站ID", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "classNo", value = "班结ID", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "classesDayOrNight", value = "班次", dataType = "String", paramType = "query")
    })
    public TableDataInfo classReportList(ClassSettlement classSettlement) {
        if (StringUtils.isNotBlank(classSettlement.getBeginTime()) && StringUtils.isNotBlank(classSettlement.getEndTime())) {
            // 将字符串转换为LocalDate类型
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDate beginDate = LocalDate.parse(classSettlement.getBeginTime(), formatter);
            LocalDate endDate = LocalDate.parse(classSettlement.getEndTime(), formatter);

            // 计算两个日期之间的差值
            long daysBetween = ChronoUnit.DAYS.between(beginDate, endDate);

            // 如果差值超过一个月，返回失败
            if (daysBetween > 31) {
                List<ClassSettlement> betweenTime = new ArrayList<>();
                TableDataInfo rspData = new TableDataInfo();
                rspData.setCode(HttpStatus.ERROR);
                rspData.setMsg("仅可查询一个月");
                rspData.setRows(betweenTime);
                rspData.setTotal((long) 0);
                return rspData;
            }
        } else {
            // 开始时间和结束时间为空的逻辑
            LocalDate today = LocalDate.now(); // 当前日期
            LocalDate sevenDaysAgo = today.minusDays(7); // 当前日期往前7天的日期

            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); // 定义日期时间格式化模式

            LocalDateTime beginTime = LocalDateTime.of(sevenDaysAgo, LocalTime.MIN); // 开始时间为当天的最早时间（00:00:00）
            LocalDateTime endTime = LocalDateTime.of(today, LocalTime.MAX); // 结束时间为当天的最晚时间（23:59:59）

            String beginTimeStr = beginTime.format(formatter); // 格式化开始时间为字符串
            String endTimeStr = endTime.format(formatter); // 格式化结束时间为字符串

// 将开始时间和结束时间的字符串赋值给相应的变量
            classSettlement.setBeginTime(beginTimeStr);
            classSettlement.setEndTime(endTimeStr);
        }
        LoginUser currentUser = SecurityUtils.getLoginUser();
        SysUser user = currentUser.getUser();
        startPage();
        if (user.getUserLevel() == null) {
            //   classSettlement.setEnterpriseId(user.getEnterpriseId());
        } else if (user.getUserLevel() != null && user.getUserLevel().equals("1")) {
            classSettlement.setEnterpriseId(user.getEnterpriseId());
        } else if (user.getUserLevel().equals("2")) {
            classSettlement.setStationId(user.getStationId());
        }else if(SecurityUtils.isPartner()){
            EnterpriseAndStationVo itemIds = stationService.getItemIds(currentUser.getUser());
            List<Long> enterpriseIds = itemIds.getEnterpriseIds();
            if (enterpriseIds != null && enterpriseIds.size()>0) {
                classSettlement.setEnterpriseIdListForAuthor(enterpriseIds);
            } else {
                throw new CustomException(UserConstants.NO_ENTERPRISE);
            }
        }

        List<ReportSettlement> list = classSettlementService.selectReportClassList(classSettlement);
        return getDataTable(list);
    }




    @PostMapping("/updateClassTime")
    @ApiOperation("更新班次时间")
    public ResponseEntity<String> updateShiftTime(@RequestBody StationClassTimeDto timeDto) {
        SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
        try {


            Time dayShiftStartTime = null;
            Time dayShiftEndTime = null;
            Time nightShiftStartTime = null;
            Time nightShiftEndTime = null;

            if (timeDto.getDayShiftStartTime() != null) {
                dayShiftStartTime = new Time(timeFormat.parse(timeDto.getDayShiftStartTime()).getTime());
            }
            if (timeDto.getDayShiftEndTime() != null) {
                dayShiftEndTime = new Time(timeFormat.parse(timeDto.getDayShiftEndTime()).getTime());
            }
            if (timeDto.getNightShiftStartTime() != null) {
                nightShiftStartTime = new Time(timeFormat.parse(timeDto.getNightShiftStartTime()).getTime());
            }
            if (timeDto.getNightShiftEndTime() != null) {
                nightShiftEndTime = new Time(timeFormat.parse(timeDto.getNightShiftEndTime()).getTime());
            }
            int result =0;
            // 使用转换后的Time对象进行后续操作
            if (dayShiftStartTime == null || dayShiftEndTime == null || nightShiftStartTime == null || nightShiftEndTime == null){
                // 调用service层方法进行更新
                result  = classSettlementService.updateDayShiftTimeById(dayShiftStartTime, dayShiftEndTime, nightShiftStartTime, nightShiftEndTime,timeDto);
            }else{
                // 检查白班和夜班时间是否有交集
                if (hasIntersection(dayShiftStartTime, dayShiftEndTime, nightShiftStartTime, nightShiftEndTime)) {
                    return ResponseEntity.badRequest().body("白班和夜班时间有交集，更新失败");
                }
                // 调用service层方法进行更新
                 result = classSettlementService.updateDayShiftTimeById(dayShiftStartTime, dayShiftEndTime, nightShiftStartTime, nightShiftEndTime,timeDto);
            }
            if (result > 0) {
                return ResponseEntity.ok("更新成功");
            } else {
                return ResponseEntity.badRequest().body("更新失败");
            }
        } catch (ParseException e) {
            // 处理解析异常
            e.printStackTrace();
            return ResponseEntity.badRequest().body("时间解析异常");
        }
    }

    @GetMapping("getDayClassTime")
    @ApiOperation("根据查询班次时间")
    public StationClassTimeVo getDayShiftTimeByStationId() {
        StationClassTimeVo a = classSettlementService.selectDayShiftTimeById();

        return a;
    }

    private boolean hasIntersection(Time startTime1, Time endTime1, Time startTime2, Time endTime2) {
        return startTime1.before(endTime2) && startTime2.before(endTime1);
    }
    /**
     * 查询班结汇总
     */
    @GetMapping("/classSettlementSum")
    @ApiOperation("班结汇总")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "beginTime", value = "开始时间", dataType = "String", paramType = "query", example = "2023-05-25 10:00:00"),
            @ApiImplicitParam(name = "endTime", value = "截止时间", dataType = "String", paramType = "query", example = "2023-05-25 18:00:00"),
            @ApiImplicitParam(name = "enterpriseId", value = "企业ID", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "stationId", value = "油站ID", dataType = "Long", paramType = "query")
    })
    public ClassSettlement classSettlementSum(ClassSettlement classSettlement) {
        if (StringUtils.isNotBlank(classSettlement.getBeginTime()) && StringUtils.isNotBlank(classSettlement.getEndTime())) {
            // 将字符串转换为LocalDate类型
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDate beginDate = LocalDate.parse(classSettlement.getBeginTime(), formatter);
            LocalDate endDate = LocalDate.parse(classSettlement.getEndTime(), formatter);

            // 计算两个日期之间的差值
            long daysBetween = ChronoUnit.DAYS.between(beginDate, endDate);

            // 如果差值超过一个月，返回失败
            if (daysBetween > 31) {
//                ClassSettlement rspData = null;

                return null;
            }
        } else {
            // 开始时间和结束时间为空的逻辑
            LocalDate today = LocalDate.now(); // 当前日期
            LocalDate sevenDaysAgo = today.minusDays(7); // 当前日期往前7天的日期

            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); // 定义日期时间格式化模式

            LocalDateTime beginTime = LocalDateTime.of(sevenDaysAgo, LocalTime.MIN); // 开始时间为当天的最早时间（00:00:00）
            LocalDateTime endTime = LocalDateTime.of(today, LocalTime.MAX); // 结束时间为当天的最晚时间（23:59:59）

            String beginTimeStr = beginTime.format(formatter); // 格式化开始时间为字符串
            String endTimeStr = endTime.format(formatter); // 格式化结束时间为字符串

// 将开始时间和结束时间的字符串赋值给相应的变量
            classSettlement.setBeginTime(beginTimeStr);
            classSettlement.setEndTime(endTimeStr);
        }
        LoginUser currentUser = SecurityUtils.getLoginUser();
        SysUser user = currentUser.getUser();
        startPage();
        if (user.getUserLevel() == null) {
            //   classSettlement.setEnterpriseId(user.getEnterpriseId());
        } else if (user.getUserLevel() != null && user.getUserLevel().equals("1")) {
            classSettlement.setEnterpriseId(user.getEnterpriseId());
            classSettlement.setOpenStaffClass(1);
        } else if (user.getUserLevel().equals("2")) {
            classSettlement.setStationId(user.getStationId());
            classSettlement=   payOrderService.classSettlementtimeSetting(classSettlement,currentUser.getUser().getStationId());
            Station station1 = stationService.selectStationById(classSettlement.getStationId());
            classSettlement.setOpenStaffClass(station1.getOpenStaffClass());
        }else if(SecurityUtils.isPartner()){
            EnterpriseAndStationVo itemIds = stationService.getItemIds(currentUser.getUser());
            List<Long> enterpriseIds = itemIds.getEnterpriseIds();
            if (enterpriseIds != null && enterpriseIds.size()>0) {
                classSettlement.setEnterpriseIdListForAuthor(enterpriseIds);
            } else {
                throw new CustomException(UserConstants.NO_ENTERPRISE);
            }
        }
        ClassSettlement classSettlementsum = new ClassSettlement();
        String sign = sysUserService.getEmployeeSign(user.getUserId());
        // 员工权限
        if(user!=null && sign.equals("1")){
            classSettlement.setCreateUser(user.getUserId());
            classSettlementsum=  classSettlementService.selectClassSettlementStaffSummary(classSettlement);
        }else{

            classSettlementsum= classSettlementService.selectClassSettlementSummary(classSettlement);
        }
        if (classSettlementsum != null) {
            BigDecimal totalWithdrawalAmount = classSettlementsum.getTotalWithdrawalAmount();
            if (totalWithdrawalAmount != null) {
                // 使用setScale方法设置小数位数为2，并且使用HALF_DOWN舍入模式（即去尾法）
                BigDecimal roundedAmount = totalWithdrawalAmount.setScale(2, RoundingMode.HALF_DOWN);

                // 将设置好的值再赋回给TotalWithdrawalAmount字段
                classSettlementsum.setTotalWithdrawalAmount(roundedAmount);
            }
            return classSettlementsum;
        }else {
            ClassSettlement errclassSettlementsum = new ClassSettlement();
            return errclassSettlementsum;
        }

    }



    /**
     * 查询班结汇总
     */
    @GetMapping("/classReportSum")
    @ApiOperation("报表汇总")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "beginTime", value = "开始时间", dataType = "String", paramType = "query", example = "2023-05-25 10:00:00"),
            @ApiImplicitParam(name = "endTime", value = "截止时间", dataType = "String", paramType = "query", example = "2023-05-25 18:00:00"),
            @ApiImplicitParam(name = "enterpriseId", value = "企业ID", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "stationId", value = "油站ID", dataType = "Long", paramType = "query")
    })
    public ReportSettlement classReportSum(ClassSettlement classSettlement) {
        if (StringUtils.isNotBlank(classSettlement.getBeginTime()) && StringUtils.isNotBlank(classSettlement.getEndTime())) {

            // 将字符串转换为LocalDate类型
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDate beginDate = LocalDate.parse(classSettlement.getBeginTime(), formatter);
            LocalDate endDate = LocalDate.parse(classSettlement.getEndTime(), formatter);

            // 计算两个日期之间的差值
            long daysBetween = ChronoUnit.DAYS.between(beginDate, endDate);

            // 如果差值超过一个月，返回失败
            if (daysBetween > 31) {
//                ClassSettlement rspData = null;

                return null;
            }
        } else {
            // 开始时间和结束时间为空的逻辑
            LocalDate today = LocalDate.now(); // 当前日期
            LocalDate sevenDaysAgo = today.minusDays(7); // 当前日期往前7天的日期

            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); // 定义日期时间格式化模式

            LocalDateTime beginTime = LocalDateTime.of(sevenDaysAgo, LocalTime.MIN); // 开始时间为当天的最早时间（00:00:00）
            LocalDateTime endTime = LocalDateTime.of(today, LocalTime.MAX); // 结束时间为当天的最晚时间（23:59:59）

            String beginTimeStr = beginTime.format(formatter); // 格式化开始时间为字符串
            String endTimeStr = endTime.format(formatter); // 格式化结束时间为字符串

// 将开始时间和结束时间的字符串赋值给相应的变量
            classSettlement.setBeginTime(beginTimeStr);
            classSettlement.setEndTime(endTimeStr);
        }
        LoginUser currentUser = SecurityUtils.getLoginUser();
        SysUser user = currentUser.getUser();
        startPage();
        if (user.getUserLevel() == null) {
            //   classSettlement.setEnterpriseId(user.getEnterpriseId());
        } else if (user.getUserLevel() != null && user.getUserLevel().equals("1")) {
            classSettlement.setEnterpriseId(user.getEnterpriseId());
        } else if (user.getUserLevel().equals("2")) {
            classSettlement.setStationId(user.getStationId());
        }else if(SecurityUtils.isPartner()){
            EnterpriseAndStationVo itemIds = stationService.getItemIds(currentUser.getUser());
            List<Long> enterpriseIds = itemIds.getEnterpriseIds();
            if (enterpriseIds != null && enterpriseIds.size()>0) {
                classSettlement.setEnterpriseIdListForAuthor(enterpriseIds);
            } else {
                throw new CustomException(UserConstants.NO_ENTERPRISE);
            }
        }

        ReportSettlement classSettlementsum= classSettlementService.selectClassReportmentSummary(classSettlement);


        if (classSettlementsum != null) {
            BigDecimal totalWithdrawalAmount = classSettlementsum.getTotalWithdrawalAmount();
            if (totalWithdrawalAmount != null) {
                // 使用setScale方法设置小数位数为2，并且使用HALF_DOWN舍入模式（即去尾法）
                BigDecimal roundedAmount = totalWithdrawalAmount.setScale(2, RoundingMode.HALF_DOWN);

                // 将设置好的值再赋回给TotalWithdrawalAmount字段
                classSettlementsum.setTotalWithdrawalAmount(roundedAmount);
            }
            return classSettlementsum;
        }else {
            ReportSettlement errclassSettlementsum = new ReportSettlement();
            return errclassSettlementsum;
        }

    }


    /**
     *
     */
    @Log(title = "班结", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(ClassSettlement classSettlement) {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        SysUser user = currentUser.getUser();
        if (user.getUserLevel() != null) {
            if (user.getUserLevel() == null) {
                //   classSettlement.setEnterpriseId(user.getEnterpriseId());
            } else if (user.getUserLevel() != null && user.getUserLevel().equals("1")) {
                classSettlement.setEnterpriseId(user.getEnterpriseId());
                classSettlement.setOpenStaffClass(1);
            } else if (user.getUserLevel().equals("2")) {
                classSettlement.setStationId(user.getStationId());
                Station station1 = stationService.selectStationById(classSettlement.getStationId());
                classSettlement.setOpenStaffClass(station1.getOpenStaffClass());
            }
        }

//        //判断是否多站
//        Station station = new Station();
//        station.setDeleteStatus("0");
//
//
//        List<Station> stations = new ArrayList<>();
//        //油企账号
//        if(user.getUserLevel().equals("1")){
//            station.setEnterpriseId(user.getEnterpriseId());
//            station.setStatus("1");
//            stations  = stationService.selectStationList(station);
//        }
//
//       if(user.getUserLevel().equals("2")){
//           Station stationById = stationService.selectStationById(user.getStationId());
//           station.setEnterpriseId(stationById.getEnterpriseId());
//           station.setStatus("1");
//           stations  = stationService.selectStationList(station);
//       }

        List<ClassSettlement> list = new ArrayList<>();

        String sign = sysUserService.getEmployeeSign(user.getUserId());
            // 员工权限
        if(user!=null && sign.equals("1")){
            list= classSettlementService.selectClassSettlementStaffSummaryList(classSettlement);
        }else{
            list= classSettlementService.selectClassSettlementSummaryList(classSettlement);
        }


        for(ClassSettlement item:list){
            if (item.getTotalWithdrawalAmount() != null) {
                item.setTotalWithdrawalAmount(item.getTotalWithdrawalAmount().setScale(2, RoundingMode.DOWN));
            } else {
                item.setTotalWithdrawalAmount(BigDecimal.ZERO.setScale(2, RoundingMode.DOWN));
            }
        }
        ExcelUtil<ClassSettlement> util = new ExcelUtil<ClassSettlement>(ClassSettlement.class);
        return util.exportExcel(list, "classSettlement");
//        if(CollectionUtils.isNotEmpty(stations) && stations.size() > 1){
//            ModelMapper modelMapper = new ModelMapper();
//            List<ClassSettlementFieldVo> voList = list.stream().map(m -> modelMapper.map(m, ClassSettlementFieldVo.class)).collect(Collectors.toList());
//
//            ExcelUtil<ClassSettlementFieldVo> util = new ExcelUtil<>(ClassSettlementFieldVo.class);
//            AjaxResult res = util.exportExcel(voList, "classSettlement");
//            return res;
//
//        }
//        ExcelUtil<ClassSettlement> util = new ExcelUtil<ClassSettlement>(ClassSettlement.class);
//        AjaxResult classSettlement1 = util.exportExcel(list, "classSettlement");
//        return list;
    }
    @ApiOperation(value = "testBusinessDailyReport")
    @GetMapping("/testBusinessDailyReport")
    @ResponseBody
    public BusinessDailyReport insertBusinessDailyReport(Long stationId) throws Exception {
        BusinessDailyReport businessDailyReport = new BusinessDailyReport();
        classSettlementService.insertBusinessDailyReport(stationId,2,"1",null,null);

//        classSettlementService.insertBusinessDailyReportTest(stationId);
        return businessDailyReport;

    }

    @ApiOperation(value = "testBusinessDailyReport2")
    @GetMapping("/testBusinessDailyReport2")
    public void createClassReportOnEight(){
        Station checkStation = new Station();
        checkStation.setStatus("1");
        checkStation.setDeleteStatus("0");
        List<Station> stationList=  stationService.selectStationList(checkStation);
        for (Station station:stationList){
            try {
                classSettlementService.insertBusinessDailyReport(station.getStationId(), 2, "1", null, null);
            } catch (Exception e) {

                e.printStackTrace();
            }
   }

    }


    /**
     * 获取班结详细信息
     */
    @GetMapping(value = "/{classNo}")
    @ApiOperation("班结详情")
    public AjaxResult getInfo(@PathVariable("classNo") String classNo) {
        if (classNo == null || classNo.equals("")) {
            return AjaxResult.error("参数错误");
        }
        return AjaxResult.success( classSettlementService.classInfoByClassNo(classNo));
    }





    /**
     * 获取班结详细信息
     */
    @GetMapping(value = "/getReport")
    @ApiOperation("交接班日报表详情")
    public AjaxResult getReport(ReportSettlement reportSettlement) {

        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> queryMap = new HashMap<String, Object>();
        queryMap.put("timeOnTrade", reportSettlement.getTimeOnTrade());
        queryMap.put("stationId",reportSettlement.getStationId());

        Station station = stationService.selectStationById(reportSettlement.getStationId());
        ClassSettlementCard form = new ClassSettlementCard();
        form.setTimeOnTrade(reportSettlement.getTimeOnTrade());
        form.setStationId(reportSettlement.getStationId());
        List<ClassSettlementCard> classSettlementCards = classSettlementCardService.selectClassReportCardList(form);
        CardClassSettDto settDto = countCardSett(classSettlementCards); //电子卡汇总数据

        List<Map<String, Object>> queryGroupByOil = classSettlementService.queryReportByOil(queryMap);
// 根据油品分组查询统计信息
        List<Map<String, Object>> queryGroupByPayType = classSettlementService.queryReportByPayType(queryMap,settDto);
// 根据支付方式分组查询统计信息
        List<Map<String, Object>> queryGroupByOilGun = classSettlementService.queryReportByOilGun(queryMap);
// 根据油枪号分组查询统计信息
      BigDecimal   allTransaction = classSettlementService.getAllTransaction(queryMap,settDto);

        int   allNewPeople = classSettlementService.getAllNewPeople(queryMap);

        ClassSettlement classSettlement = new ClassSettlement();
        classSettlement.setStationId(reportSettlement.getStationId());
        classSettlement.setTimeOnTrade(reportSettlement.getTimeOnTrade());
        BigDecimal totalWordCount =   classSettlementService.totalWordCount(classSettlement);
        List<Map<String, Object>> shiftHandover = classSettlementService.getShiftHandover(queryMap);

//没用

        resultMap.put("queryGroupByOil", queryGroupByOil);
        resultMap.put("queryGroupByPayType", queryGroupByPayType);
        resultMap.put("queryGroupByOilGun", queryGroupByOilGun);
        resultMap.put("allTransaction", allTransaction);
        resultMap.put("allNewPeople", allNewPeople);
        resultMap.put("totalWordCount", totalWordCount);
        resultMap.put("shiftHandover", shiftHandover);
        resultMap.put("isShowCommission",  station.getIsShowCommission());



        return AjaxResult.success(resultMap);
    }

    /**
     * 获取班结详细信息
     * 为了暴露接口给双屏机调用
     */
    @GetMapping(value = "/dualScreen/{classNo}")
    public AjaxResult getOutInfo(@PathVariable("classNo") String classNo) {
        return getInfo(classNo);
    }

    /**
     * 班结
     */
    @GetMapping("/stationCreateClassSe")
    public AjaxResult stationCreateClassSe(ClassSettlement classSettlement) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        List<Map<String, Object>> resultMapList = new ArrayList<Map<String, Object>>();
        if (classSettlement.getClassEndTime() == null) {
            return AjaxResult.error("参数不完整");
        }
        LoginUser currentUser = SecurityUtils.getLoginUser();
        SysUser user = currentUser.getUser();
        classSettlement.setStationId(currentUser.getUser().getStationId());
        classSettlement.setCreateUser(user.getUserId());
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat simFmtBef = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat simFmtAft = new SimpleDateFormat("HHmm");
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("stationId", classSettlement.getStationId());
        Map<String, Object> endTimeMap = classSettlementService.queryLastEndTime(params);

        params.clear();
        params.put("serviceType", "BGS");//班结的时候多维度分组查询
        String startTime = null;
        if (endTimeMap != null && endTimeMap.containsKey("classEndTime") && endTimeMap.get("classEndTime") != null) {
//            params.put("createStartTime","2021-07-10 00:00:00");
            startTime = endTimeMap.get("classEndTime").toString();
        }
        params.put("createStartTime", startTime);
        params.put("createEndTime", fmt.format(classSettlement.getClassEndTime()));
        params.put("stationId", classSettlement.getStationId());
        List<ClassSettlement> classSettlements = classSettlementService.queryUntreatedData(params);
        List<ClassSettlementCard> classSettlementCards = classSettlementCardService.queryUntreatedData(params);

        String no = simFmtBef.format(classSettlement.getClassEndTime()) + classSettlement.getStationId() + simFmtAft.format(classSettlement.getClassEndTime());
        for (ClassSettlement settlement : classSettlements) {
            settlement.setCreateName(user.getUserName());
            settlement.setCreateUser(Long.valueOf(user.getUserId()));
            settlement.setEquipmentCode("PC");
            //设置通联支付的时候的班结号码
            settlement.setClassNo(no);
            try {
                if (startTime != null) {
                    settlement.setClassStartTime(fmt.parse(startTime));
                }

            } catch (ParseException e) {
                e.printStackTrace();
            }
//            settlement.setEnterpriseId(Long.valueOf(user.getEnterpriseId()));
            settlement.setNote(classSettlement.getNote());
            settlement.setClassNo(no);
            classSettlementService.insertClassSettlement(settlement);
        }
        for (ClassSettlementCard settlement : classSettlementCards) {
            settlement.setCreateName(user.getUserName());
            settlement.setCreateUser(Long.valueOf(user.getUserId()));
            settlement.setEquipmentCode("PC");
            settlement.setCreateTime(new Date());
            try {
                if (startTime != null) {
                    settlement.setClassStartTime(fmt.parse(startTime));
                }

            } catch (ParseException e) {
                e.printStackTrace();
            }
//            settlement.setEnterpriseId(Long.valueOf(user.getEnterpriseId()));
            settlement.setNote(classSettlement.getNote());
            settlement.setClassNo(no);
            classSettlementCardService.insertClassSettlementCard(settlement);
        }
        ClassSettlement pushClass = new ClassSettlement();
        pushClass.setClassNo(no);
        pushClass.setStationId(classSettlement.getStationId());
        pushClass.setClassEndTime(classSettlement.getClassEndTime());
        try {
            pushClass.setClassStartTime(fmt.parse(startTime));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        getPushMessage(pushClass);

        resultMap.put("classNo", no);
        return AjaxResult.success(resultMap);
    }


    @GetMapping(path = {"/lastTimeByUserIdBGApi","/anony/lastTimeByUserIdBGApi"})
    public AjaxResult lastTimeByUserIdBGApi(Long userId) throws InterruptedException {

        SysUser uuser =   sysUserService.getById(userId);
        List<Long> roleIds = classSettlementService.selectSysUserByCreateUser(userId);
        List<SysRole> roles = new ArrayList<>();
        for(Long roleId:roleIds){
            SysRole a = new SysRole();
            a.setRoleId(roleId);
            roles.add(a);
        }
        uuser.setRoles(roles);
        Map<String, Object> params = new HashMap<String, Object>();
        String startTime = null;
        String sign = sysUserService.getEmployeeSign(uuser.getUserId());
        // 员工权限
        if(uuser!=null && sign.equals("1")){

            Station station =  stationService.selectStationById(uuser.getStationId());
            params.put("stationId", station.getStationId());
            params.put("oilPersonnelId", "0");
            if(station.getOpenStaffClass() == 1) {
                params.put("oilPersonnelId",userId);
            }

            Map<String, Object> endTimeMap = classSettlementService.queryLastEndTimeStaff(params);
            if (endTimeMap == null ){
                endTimeMap = classSettlementService.queryLastEndTime(params);
            }
            if (endTimeMap != null && endTimeMap.containsKey("classStartTime") && endTimeMap.get("classStartTime") != null) {
                startTime = endTimeMap.get("classStartTime").toString();
            }else{
                startTime = "2024-01-01 09:00:00";
            }

        }else{

            params.put("stationId", uuser.getStationId());

            Map<String, Object> endTimeMap = classSettlementService.queryLastEndTime(params);
            if (endTimeMap != null && endTimeMap.containsKey("classStartTime") && endTimeMap.get("classStartTime") != null) {
                startTime = endTimeMap.get("classStartTime").toString();
            }else{
                startTime = "2024-01-01 09:00:00";
            }

        }
        return  AjaxResult.success("success",startTime);
    }
    @GetMapping(path = {"/isStaffBGApi","/anony/isStaffBGApi"})
    public AjaxResult isStaffBGApi(Long userId) throws InterruptedException {

        SysUser uuser =   sysUserService.getById(userId);
        List<Long> roleIds = classSettlementService.selectSysUserByCreateUser(userId);
        List<SysRole> roles = new ArrayList<>();
        for(Long roleId:roleIds){
            SysRole a = new SysRole();
            a.setRoleId(roleId);
            roles.add(a);
        }
        uuser.setRoles(roles);
        String sign = sysUserService.getEmployeeSign(uuser.getUserId());
        // 员工权限
        if(uuser!=null && sign.equals("1")){
                Station station =  stationService.selectStationById(uuser.getStationId());
                if(station.getOpenStaffClass() == 1) {
//                   员工且开启
                    return AjaxResult.success("cg",2);
                }else{
//                    员工且关闭
                    return AjaxResult.success("cg",3);
                }
        }else{
            Station station =  stationService.selectStationById(uuser.getStationId());
            if(station.getOpenStaffClass() == 1) {
                //                   油站且开启
                return AjaxResult.success("cg",4);
            }else{
                //                   油站且关闭
                return AjaxResult.success("cg",1);
            }
        }


    }
    @GetMapping(path = {"/isStaffUserBGApi","/anony/isStaffUserBGApi"})
    public AjaxResult isStaffUserBGApi(Long userId) throws InterruptedException {

        SysUser uuser =   sysUserService.getById(userId);
        List<Long> roleIds = classSettlementService.selectSysUserByCreateUser(userId);
        List<SysRole> roles = new ArrayList<>();
        for(Long roleId:roleIds){
            SysRole a = new SysRole();
            a.setRoleId(roleId);
            roles.add(a);
        }
        uuser.setRoles(roles);
        boolean staff = StaffUtil.isStaff(uuser);
        if(staff){
            return  AjaxResult.success("cg",1);
        }else{
            return  AjaxResult.success("cg",2);
        }

    }

    /**
     * 确认班结   修复班结同步到3月22号
     */
    @GetMapping(path = {"/createClassSe","/anony/createClassSe"})
    @Transactional
    public AjaxResult createClassSe(ClassSettlement classSettlement) throws InterruptedException {
        log.info("createClassSe:{}", JSON.toJSONString(classSettlement));
        Map<String, Object> resultMap = new HashMap<String, Object>();
        List<Map<String, Object>> resultMapList = new ArrayList<Map<String, Object>>();
        if (classSettlement.getClassEndTime() == null || classSettlement.getStationId() == null) {
            return AjaxResult.error("参数不完整");
        }
        Station stationOpenStaff =  stationService.selectStationById(classSettlement.getStationId());
        classSettlement.setOpenStaffClass(0);
        SysUser user = new SysUser();
        //判断如果是自动班结传进的 使用自动班结的用户信息
        if (null == classSettlement.getCreateUser()){
            LoginUser currentUser = SecurityUtils.getLoginUser();
            user = currentUser.getUser();
            classSettlement.setCreateUser(user.getUserId());
            String sign = sysUserService.getEmployeeSign(user.getUserId());
            // 员工权限
            if(user!=null && sign.equals("1")){
                Station station =  stationService.selectStationById(classSettlement.getStationId());
               if(station.getOpenStaffClass() == 1) {
                   classSettlement.setOilPersonnelId(user.getUserId().toString());
                   classSettlement.setCreateUser(user.getUserId());
                   classSettlement.setCreateName(user.getUserName());
                   classSettlement.setOpenStaffClass(1);
               }else{
                   return AjaxResult.error("当前未开启员工班结，请开启后再操作");

               }
            }else{
                if(stationOpenStaff.getOpenStaffClass() == 1) {

                    classSettlement.setOpenStaffClass(1);
                }
            }
            //判断油站是否开启自动班结

        if (stationOpenStaff.getIsAutomaticClass() == 1){
            return AjaxResult.error("该油站已开启自动班结");
        }
        }else {
            user.setUserId(classSettlement.getCreateUser());
            user.setUserName(classSettlement.getCreateName());
            SysUser uuser =   sysUserService.getById(classSettlement.getCreateUser());
            List<Long> roleIds = classSettlementService.selectSysUserByCreateUser(classSettlement.getCreateUser());
            List<SysRole> roles = new ArrayList<>();
            for(Long roleId:roleIds){
                SysRole a = new SysRole();
                a.setRoleId(roleId);
                roles.add(a);
            }
            uuser.setRoles(roles);
            String sign = sysUserService.getEmployeeSign(uuser.getUserId());
            // 员工权限
            if(uuser!=null && sign.equals("1")){


                if(stationOpenStaff.getOpenStaffClass() == 1) {
                    classSettlement.setCreateUser(uuser.getUserId());
                    classSettlement.setCreateName(uuser.getUserName());
                    classSettlement.setOilPersonnelId(uuser.getUserId().toString());
                    classSettlement.setOpenStaffClass(1);
                }else{
                    return AjaxResult.error("当前未开启员工班结，请开启后再操作");

                }
            }else{
                if(stationOpenStaff.getOpenStaffClass() == 1) {
                    classSettlement.setOpenStaffClass(1);
                }
            }

        }

        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat simFmtBef = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat simFmtAft = new SimpleDateFormat("HHmm");
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("stationId", classSettlement.getStationId());
        params.put("oilPersonnelId", "0");
        if(stationOpenStaff.getOpenStaffClass() == 1) {
            if( classSettlement.getOilPersonnelId()!=null){
                params.put("oilPersonnelId", classSettlement.getOilPersonnelId());
            }
        }
        Map<String, Object> endTimeMap = classSettlementService.queryLastEndTimeStaff(params);
        if (endTimeMap == null ){
            endTimeMap = classSettlementService.queryLastEndTime(params);
        }
        params.clear();
        params.put("serviceType", "BGS");//班结的时候多维度分组查询
        String startTime = null;
        if (endTimeMap != null && endTimeMap.containsKey("classEndTime") && endTimeMap.get("classEndTime") != null) {
//            params.put("createStartTime","2021-07-10 00:00:00");
            startTime = endTimeMap.get("classEndTime").toString();
        }
        params.put("createStartTime", startTime);
        params.put("createEndTime", fmt.format(classSettlement.getClassEndTime()));
        params.put("stationId", classSettlement.getStationId());
        if(stationOpenStaff.getOpenStaffClass() == 1) {
            if( classSettlement.getOilPersonnelId()!=null){
                params.put("oilPersonnelId", classSettlement.getOilPersonnelId());
            }else{
                params.put("openStaffClassInStation", 1);
            }
        }


        String classesDayOrNight = classSettlementService.queryClassDayOrNight(classSettlement.getStationId(),classSettlement.getClassEndTime());
        List<ClassSettlement> classSettlements = classSettlementService.queryUntreatedData(params);
        String no = simFmtBef.format(classSettlement.getClassEndTime()) + classSettlement.getStationId() + simFmtAft.format(classSettlement.getClassEndTime());
        if(stationOpenStaff.getOpenStaffClass() == 1) {
            if( classSettlement.getOilPersonnelId()!=null){
                for (ClassSettlement settlement : classSettlements) {
                    settlement.setCreateName(user.getUserName());
                    settlement.setCreateUser(Long.valueOf(user.getUserId()));
                    settlement.setEquipmentCode("PC");
                    settlement.setClassNo(no);
                    settlement.setIsRepairClass(0);
                    settlement.setClassesDayOrNight(classesDayOrNight);
                    try {
                        if (startTime != null) {
                            settlement.setClassStartTime(fmt.parse(startTime));
                        }
                        settlement.setClassEndTime(classSettlement.getClassEndTime());
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    settlement.setNote(classSettlement.getNote());
                    settlement.setClassNo(no);
                    classSettlementService.insertStaffClassSettlement(settlement);

                }
                if (classSettlements.size() == 0) {
                    ClassSettlement settlement = new ClassSettlement();
                    settlement.setCreateName(classSettlement.getCreateName());
                    settlement.setCreateUser(classSettlement.getCreateUser());
                    settlement.setClassNo(no);
                    if(classSettlement.getOpenStaffClass()==1){
                        settlement.setIsRepairClass(0);
                    }
                    settlement.setClassesDayOrNight(classesDayOrNight);
                    settlement.setStationId(classSettlement.getStationId());
                    settlement.setStationName(stationOpenStaff.getStationName());
                    try {
                        if (startTime != null) {
                            settlement.setClassStartTime(fmt.parse(startTime));
                        }
                        settlement.setClassEndTime(classSettlement.getClassEndTime());
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    settlement.setNote(classSettlement.getNote());
                    classSettlementService.insertStaffClassSettlement(settlement);
                }
                params.put("no",no);
                classSettlementService.selectChange4User4POSListForOrder(params);

                classSettlementService.insertAboutOil(params,no,fmt.format(classSettlement.getClassEndTime()),classSettlement.getStationId());
                classSettlementService.selectChange4User4POSListForOrder(params);

                List<ClassSettlementCard> classSettlementCards = classSettlementCardService.queryUntreatedData(params);
                CardClassSettDto settDto = countCardSett(classSettlementCards); // 电子卡交易汇总数据
                BigDecimal actualRechargeReceivedAmt =  settDto.getAllAmt();
                BigDecimal actualRechargeGiftAmt =  settDto.getTotalGiveAmt();
                for (ClassSettlementCard settlement : classSettlementCards) {
                    settlement.setCreateName(user.getUserName());
                    settlement.setCreateUser(Long.valueOf(user.getUserId()));
                    settlement.setEquipmentCode("PC");
                    settlement.setCreateTime(new Date());
                    try {
                        if (startTime != null) {
                            settlement.setClassStartTime(fmt.parse(startTime));
                        }
                        settlement.setClassEndTime(classSettlement.getClassEndTime());
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    // settlement.setEnterpriseId(Long.valueOf(user.getEnterpriseId()));
                    settlement.setNote(classSettlement.getNote());
                    settlement.setClassNo(no);
                    if (settlement.getClassEndTime() != null) {
                        classSettlementCardService.insertClassSettlementCard(settlement);
                    }

                }

                if(actualRechargeReceivedAmt!=null && actualRechargeReceivedAmt.compareTo(BigDecimal.ZERO) != 0||
                        actualRechargeGiftAmt!=null && actualRechargeGiftAmt.compareTo(BigDecimal.ZERO) != 0)
                      {
                    ClassSettlement settlementonlyactualRechargeReceivedAmt = new ClassSettlement();
                    settlementonlyactualRechargeReceivedAmt.setActualRechargeReceivedAmt(actualRechargeReceivedAmt);
                    settlementonlyactualRechargeReceivedAmt.setActualRechargeGiftAmt(actualRechargeGiftAmt);
                    settlementonlyactualRechargeReceivedAmt.setClassNo(no);
                    if(classSettlement.getOpenStaffClass()==1){
                        settlementonlyactualRechargeReceivedAmt.setIsRepairClass(0);
                    }
                    settlementonlyactualRechargeReceivedAmt.setClassesDayOrNight(classesDayOrNight);
                    settlementonlyactualRechargeReceivedAmt.setCreateUser(Long.valueOf(user.getUserId()));
                    settlementonlyactualRechargeReceivedAmt.setEquipmentCode("PC");
                    settlementonlyactualRechargeReceivedAmt.setStationId( stationOpenStaff.getStationId());
                    settlementonlyactualRechargeReceivedAmt.setStationName(stationOpenStaff.getStationName());
                    settlementonlyactualRechargeReceivedAmt.setCreateName(user.getUserName());
                    try {
                        if (startTime != null) {
                            settlementonlyactualRechargeReceivedAmt.setClassStartTime(fmt.parse(startTime));
                        }
                        settlementonlyactualRechargeReceivedAmt.setClassEndTime(classSettlement.getClassEndTime());
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    settlementonlyactualRechargeReceivedAmt.setNote(classSettlement.getNote());
                    classSettlementService.insertStaffClassSettlement(settlementonlyactualRechargeReceivedAmt);
                }
                ClassSettlement pushClass = new ClassSettlement();
                pushClass.setClassNo(no);
                pushClass.setStationId(classSettlement.getStationId());
                pushClass.setClassEndTime(classSettlement.getClassEndTime());
                try {
                    if (startTime != null) {
                        pushClass.setClassStartTime(fmt.parse(startTime));
                    }

                } catch (ParseException e) {
                    e.printStackTrace();
                }

                resultMap.put("classNo", no);
                log.info("pushClass{}",pushClass);
                classSettlementPrintService.getPushMessage(pushClass);
                return AjaxResult.success(resultMap);
            }
        }


        List<ClassSettlementCard> classSettlementCards = classSettlementCardService.queryUntreatedData(params);
//        // 调用方法获取总金额
//        BigDecimal actualRechargeReceivedAmt = customerCardUseRecordService.getTotalAmtByConditions(params);
//        //电子卡赠送金额
//        BigDecimal actualRechargeGiftAmt = customerCardUseRecordService.getTotalPresentAmtByConditions(params);

        CardClassSettDto settDto = countCardSett(classSettlementCards); // 电子卡交易汇总数据
        BigDecimal actualRechargeReceivedAmt = classSettlementService.forActualRechargeReceivedAmt(settDto,params) ;
        BigDecimal killCouponAmt = classSettlementService.forKillCouponAmt(params) ;
        ClassSettlementCard superPay = classSettlementService.querySuperPay(params) ;

//                优惠券核销，然后把核销的金额统计起来，放进优惠券金额汇总里面
        BigDecimal actualRechargeGiftAmt = settDto.getTotalGiveAmt();
        BigDecimal totalRechargeWithdrawalAmount = settDto.getTotalWithdrawalAmount();
        BigDecimal saleActivityAmt =  classSettlementService.forSaleActivityAmt(params) ;
        BigDecimal saleActivityCom =  classSettlementService.forSaleActivityCom(params) ;
        BigDecimal refSaleActivityAmt =  classSettlementService.refSaleActivityAmt(params) ;



        ClassSettlementCard physicalCardRef = classSettlementService.queryPhysicalCardRef(params);

        BigDecimal totalRechargeRefundAmt = settDto.getTotalRefundAmt().add(physicalCardRef.getAmt()!=null?physicalCardRef.getAmt():BigDecimal.ZERO);


        BigDecimal superPayAmt = superPay.getWithdrawalAmount();
        BigDecimal superPayRef = superPay.getRefundAmount();
        Object stationId = params.get("stationId");
        Station station = stationService.selectStationById((Long)stationId);
        PayOrder payOrder = new PayOrder();
        payOrder.setStationId(classSettlement.getStationId());
        if (endTimeMap != null && endTimeMap.containsKey("classEndTime") && endTimeMap.get("classEndTime") != null) {
            payOrder.setStartTime(endTimeMap.get("classEndTime").toString());
        }
        payOrder.setStatus("1");
        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime localDateTime = LocalDateTime.ofInstant(classSettlement.getClassEndTime().toInstant(), ZoneId.systemDefault());
        String formattedDate = outputFormatter.format(localDateTime);
        payOrder.setEndTime(formattedDate);
         //        List<PayOrder> within7DaysData = payOrderService.selectPayOrderListUserPaytime(payOrder);
        classSettlementService.insertAboutOil(params,no,fmt.format(classSettlement.getClassEndTime()),classSettlement.getStationId());
        params.put("no",no);
        classSettlementService.selectChange4User4POSListForOrder(params);
        if(actualRechargeReceivedAmt!=null && actualRechargeReceivedAmt.compareTo(BigDecimal.ZERO) != 0||
                actualRechargeGiftAmt!=null && actualRechargeGiftAmt.compareTo(BigDecimal.ZERO) != 0||
                totalRechargeWithdrawalAmount!=null && totalRechargeWithdrawalAmount.compareTo(BigDecimal.ZERO) != 0||
                totalRechargeRefundAmt!=null && totalRechargeRefundAmt.compareTo(BigDecimal.ZERO) != 0||
                killCouponAmt!=null && killCouponAmt.compareTo(BigDecimal.ZERO) != 0||
                superPayAmt!=null && superPayAmt.compareTo(BigDecimal.ZERO) != 0||
                refSaleActivityAmt!=null && refSaleActivityAmt.compareTo(BigDecimal.ZERO) != 0||
                saleActivityAmt!=null && saleActivityAmt.compareTo(BigDecimal.ZERO) != 0){
            ClassSettlement settlementonlyactualRechargeReceivedAmt = new ClassSettlement();
            settlementonlyactualRechargeReceivedAmt.setKillCouponAmt(killCouponAmt);
            settlementonlyactualRechargeReceivedAmt.setActualRechargeReceivedAmt(actualRechargeReceivedAmt);
            settlementonlyactualRechargeReceivedAmt.setActualRechargeGiftAmt(actualRechargeGiftAmt);
            settlementonlyactualRechargeReceivedAmt.setTotalWithdrawalAmount(totalRechargeWithdrawalAmount);
            settlementonlyactualRechargeReceivedAmt.setRefundAmt(totalRechargeRefundAmt);
            settlementonlyactualRechargeReceivedAmt.setClassNo(no);
            if(classSettlement.getOpenStaffClass()==1){
                settlementonlyactualRechargeReceivedAmt.setIsRepairClass(2);
            }else{
                settlementonlyactualRechargeReceivedAmt.setIsRepairClass(1);
            }
            settlementonlyactualRechargeReceivedAmt.setClassesDayOrNight(classesDayOrNight);
            settlementonlyactualRechargeReceivedAmt.setCreateUser(Long.valueOf(user.getUserId()));
            settlementonlyactualRechargeReceivedAmt.setEquipmentCode("PC");
            settlementonlyactualRechargeReceivedAmt.setStationId((Long) stationId);
            settlementonlyactualRechargeReceivedAmt.setStationName(station.getStationName());
            settlementonlyactualRechargeReceivedAmt.setSuperPayAmt(superPayAmt);
            settlementonlyactualRechargeReceivedAmt.setSuperPayRef(superPayRef);
            settlementonlyactualRechargeReceivedAmt.setSaleActivityAmt(saleActivityAmt);
            settlementonlyactualRechargeReceivedAmt.setSaleActivityRef(refSaleActivityAmt);
            if(superPay!=null){
//                空支付的一列暂时给超级会员用
                settlementonlyactualRechargeReceivedAmt.setCommission(superPay.getServiceCharge()!=null?superPay.getServiceCharge():BigDecimal.ZERO);

            }
            if(saleActivityCom!=null){
                settlementonlyactualRechargeReceivedAmt.setSaleActivityCom(saleActivityCom);
            }
            settlementonlyactualRechargeReceivedAmt.setCreateName(user.getUserName());
            try {
                if (startTime != null) {
                    settlementonlyactualRechargeReceivedAmt.setClassStartTime(fmt.parse(startTime));
                }
                settlementonlyactualRechargeReceivedAmt.setClassEndTime(classSettlement.getClassEndTime());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            settlementonlyactualRechargeReceivedAmt.setNote(classSettlement.getNote());
            classSettlementService.insertClassSettlement(settlementonlyactualRechargeReceivedAmt);
        }
        for (ClassSettlement settlement : classSettlements) {
            settlement.setCreateName(user.getUserName());
            settlement.setCreateUser(Long.valueOf(user.getUserId()));
            if (StringUtils.isNotBlank(classSettlement.getEquipmentCode())) {
                settlement.setEquipmentCode(classSettlement.getEquipmentCode());
            }else{
                settlement.setEquipmentCode("PC");
            }
            settlement.setClassNo(no);
            if(classSettlement.getOpenStaffClass()==1){
                settlement.setIsRepairClass(2);
            }else{
                settlement.setIsRepairClass(1);
            }
            settlement.setClassesDayOrNight(classesDayOrNight);
            try {
                if (startTime != null) {
                    settlement.setClassStartTime(fmt.parse(startTime));
                }
                settlement.setClassEndTime(classSettlement.getClassEndTime());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            settlement.setNote(classSettlement.getNote());
            settlement.setClassNo(no);
            classSettlementService.insertClassSettlement(settlement);

        }
        //        无数据新增0班结 缺少新增字段
        if (classSettlements.size() == 0) {
            ClassSettlement settlement = new ClassSettlement();
            settlement.setCreateName(user.getUserName());
            settlement.setCreateUser(Long.valueOf(user.getUserId()));
            settlement.setClassNo(no);
            if(classSettlement.getOpenStaffClass()==1){
                settlement.setIsRepairClass(2);
            }else{
                settlement.setIsRepairClass(1);
            }
            settlement.setClassesDayOrNight(classesDayOrNight);
            settlement.setStationId((Long) stationId);
            settlement.setStationName(station.getStationName());
            if (StringUtils.isNotBlank(classSettlement.getEquipmentCode())) {
                settlement.setEquipmentCode(classSettlement.getEquipmentCode());
            }else{
                settlement.setEquipmentCode("PC");
            }
            try {
                if (startTime != null) {
                    settlement.setClassStartTime(fmt.parse(startTime));
                }
                settlement.setClassEndTime(classSettlement.getClassEndTime());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            settlement.setNote(classSettlement.getNote());
            classSettlementService.insertClassSettlement(settlement);
        }
        for (ClassSettlementCard settlement : classSettlementCards) {
            settlement.setCreateName(user.getUserName());
            settlement.setCreateUser(Long.valueOf(user.getUserId()));
            if (StringUtils.isNotBlank(classSettlement.getEquipmentCode())) {
                settlement.setEquipmentCode(classSettlement.getEquipmentCode());
            }else{
                settlement.setEquipmentCode("PC");
            }
            settlement.setCreateTime(new Date());
            try {
                if (startTime != null) {
                    settlement.setClassStartTime(fmt.parse(startTime));
                }
                settlement.setClassEndTime(classSettlement.getClassEndTime());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            // settlement.setEnterpriseId(Long.valueOf(user.getEnterpriseId()));
            settlement.setNote(classSettlement.getNote());
            settlement.setClassNo(no);
            if (settlement.getClassEndTime() != null) {
                classSettlementCardService.insertClassSettlementCard(settlement);
            }

        }
        Date startTimeDate =null;
        if(startTime!=null){
            try {
                SimpleDateFormat fmtfmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
                  startTimeDate  = fmtfmt.parse(startTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        classSettlementService.insertBusinessDailyReportAsync(classSettlement.getStationId(),1,no,classSettlement.getClassEndTime(),startTimeDate);
        ClassSettlement pushClass = new ClassSettlement();
        pushClass.setClassNo(no);
        pushClass.setStationId(classSettlement.getStationId());
        pushClass.setClassEndTime(classSettlement.getClassEndTime());
        try {
            if (startTime != null) {
                pushClass.setClassStartTime(fmt.parse(startTime));
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }

        resultMap.put("classNo", no);
        log.info("pushClass{}",pushClass);
        classSettlementPrintService.getPushMessage(pushClass);
        return AjaxResult.success(resultMap);
    }

    /**
     * 确认班结开始结束油站id  修复班结
     */
    @GetMapping(path = {"/createClassSeBandEandStation"})
    @Transactional
    public AjaxResult createClassSeBandEandStation(ClassSettlement classSettlement) throws InterruptedException {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        List<Map<String, Object>> resultMapList = new ArrayList<Map<String, Object>>();

        LoginUser currentUser = SecurityUtils.getLoginUser();
        SysUser   user = currentUser.getUser();
        classSettlement.setCreateUser(user.getUserId());

        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat simFmtBef = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat simFmtAft = new SimpleDateFormat("HHmm");
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("stationId", classSettlement.getStationId());
        params.put("classNo",  classSettlement.getClassNo());
        String no = classSettlement.getClassNo();
        String[] classNo = new String[1];
        classNo[0] = no;
        Map<String, Object> startAndEndMap = classSettlementService.queryStartAndEnd(params);
        int i = classSettlementService.deleteClassSettlementByClassNos(classNo);


        params.clear();
        params.put("serviceType", "BGS");//班结的时候多维度分组查询

        if (startAndEndMap.get("classStartTime") != null) {
            params.put("createStartTime", startAndEndMap.get("classStartTime").toString());
            classSettlement.setClassStartTime((Date)startAndEndMap.get("classStartTime"));
        }
        if (startAndEndMap.get("classEndTime") != null) {
            params.put("createEndTime", startAndEndMap.get("classEndTime").toString());
            classSettlement.setClassEndTime((Date)startAndEndMap.get("classEndTime"));
        }
        if (startAndEndMap.get("isRepairClass") != null && startAndEndMap.get("isRepairClass").toString().equals("2")) {
            params.put("openStaffClassInStation", 1);

        }


        params.put("stationId", startAndEndMap.get("stationId"));
        String classesDayOrNight = classSettlementService.queryClassDayOrNight(classSettlement.getStationId(),(Date) startAndEndMap.get("classEndTime"));
        List<ClassSettlement> classSettlements = classSettlementService.queryUntreatedData(params);


        List<ClassSettlementCard> classSettlementCards = classSettlementCardService.queryUntreatedData(params);
//        // 调用方法获取总金额
//        BigDecimal actualRechargeReceivedAmt = customerCardUseRecordService.getTotalAmtByConditions(params);
//        //电子卡赠送金额
//        BigDecimal actualRechargeGiftAmt = customerCardUseRecordService.getTotalPresentAmtByConditions(params);

        CardClassSettDto settDto = countCardSett(classSettlementCards); // 电子卡交易汇总数据
        BigDecimal actualRechargeReceivedAmt = classSettlementService.forActualRechargeReceivedAmt(settDto,params) ;
        BigDecimal killCouponAmt = classSettlementService.forKillCouponAmt(params) ;
        ClassSettlementCard superPay = classSettlementService.querySuperPay(params) ;
//                优惠券核销，然后把核销的金额统计起来，放进优惠券金额汇总里面
        BigDecimal actualRechargeGiftAmt = settDto.getTotalGiveAmt();
        BigDecimal totalRechargeWithdrawalAmount = settDto.getTotalWithdrawalAmount();
        BigDecimal saleActivityAmt =  classSettlementService.forSaleActivityAmt(params) ;
        BigDecimal saleActivityCom =  classSettlementService.forSaleActivityCom(params) ;
        BigDecimal refSaleActivityAmt =  classSettlementService.refSaleActivityAmt(params) ;




        ClassSettlementCard physicalCardRef = classSettlementService.queryPhysicalCardRef(params);

        BigDecimal totalRechargeRefundAmt = settDto.getTotalRefundAmt().add(physicalCardRef.getAmt()!=null?physicalCardRef.getAmt():BigDecimal.ZERO);

        BigDecimal superPayAmt = superPay.getWithdrawalAmount();
        BigDecimal superPayRef = superPay.getRefundAmount();
        Object stationIdObj = params.get("stationId");
      Integer  stationId = (Integer)stationIdObj;
        Station station = stationService.selectStationById(stationId.longValue());
        PayOrder payOrder = new PayOrder();
        payOrder.setStationId(classSettlement.getStationId());
 if(startAndEndMap.get("classStartTime")!=null){
     payOrder.setStartTime(startAndEndMap.get("classStartTime").toString());
 }

        if (startAndEndMap.get("createEndTime") != null) {
            payOrder.setEndTime( startAndEndMap.get("classEndTime").toString());
        }

        payOrder.setStatus("1");
        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        payOrder.setEndTime(startAndEndMap.get("classEndTime").toString());
        //        List<PayOrder> within7DaysData = payOrderService.selectPayOrderListUserPaytime(payOrder);
           classSettlementService.insertAboutOil(params,no,fmt.format(classSettlement.getClassEndTime()),classSettlement.getStationId());
        params.put("no",no);
        classSettlementService.selectChange4User4POSListForOrder(params);
        if(actualRechargeReceivedAmt!=null && actualRechargeReceivedAmt.compareTo(BigDecimal.ZERO) != 0||
                actualRechargeGiftAmt!=null && actualRechargeGiftAmt.compareTo(BigDecimal.ZERO) != 0||
                totalRechargeWithdrawalAmount!=null && totalRechargeWithdrawalAmount.compareTo(BigDecimal.ZERO) != 0||
                totalRechargeRefundAmt!=null && totalRechargeRefundAmt.compareTo(BigDecimal.ZERO) != 0||
                killCouponAmt!=null && killCouponAmt.compareTo(BigDecimal.ZERO) != 0||
                superPayAmt!=null && superPayAmt.compareTo(BigDecimal.ZERO) != 0||
                refSaleActivityAmt!=null && refSaleActivityAmt.compareTo(BigDecimal.ZERO) != 0||
                saleActivityAmt!=null && saleActivityAmt.compareTo(BigDecimal.ZERO) != 0){
            ClassSettlement settlementonlyactualRechargeReceivedAmt = new ClassSettlement();
            settlementonlyactualRechargeReceivedAmt.setKillCouponAmt(killCouponAmt);
            settlementonlyactualRechargeReceivedAmt.setActualRechargeReceivedAmt(actualRechargeReceivedAmt);
            settlementonlyactualRechargeReceivedAmt.setActualRechargeGiftAmt(actualRechargeGiftAmt);
            settlementonlyactualRechargeReceivedAmt.setTotalWithdrawalAmount(totalRechargeWithdrawalAmount);
            settlementonlyactualRechargeReceivedAmt.setRefundAmt(totalRechargeRefundAmt);
            settlementonlyactualRechargeReceivedAmt.setClassNo(no);
            if (startAndEndMap.get("isRepairClass") != null && startAndEndMap.get("isRepairClass").toString().equals("2")) {
                settlementonlyactualRechargeReceivedAmt.setIsRepairClass(2);
            }else{
                settlementonlyactualRechargeReceivedAmt.setIsRepairClass(1);
            }
            settlementonlyactualRechargeReceivedAmt.setClassesDayOrNight(classesDayOrNight);
            settlementonlyactualRechargeReceivedAmt.setCreateUser(Long.valueOf(user.getUserId()));
            settlementonlyactualRechargeReceivedAmt.setEquipmentCode("PC");
            settlementonlyactualRechargeReceivedAmt.setStationId(stationId.longValue());
            settlementonlyactualRechargeReceivedAmt.setStationName(station.getStationName());
            settlementonlyactualRechargeReceivedAmt.setSuperPayAmt(superPayAmt);
            settlementonlyactualRechargeReceivedAmt.setSuperPayRef(superPayRef);
            settlementonlyactualRechargeReceivedAmt.setSaleActivityAmt(saleActivityAmt);
            settlementonlyactualRechargeReceivedAmt.setSaleActivityRef(refSaleActivityAmt);
            if(superPay!=null){
//                空支付的一列暂时给超级会员用
                settlementonlyactualRechargeReceivedAmt.setCommission(superPay.getServiceCharge()!=null?superPay.getServiceCharge():BigDecimal.ZERO);

            }
            if(saleActivityCom!=null){
                settlementonlyactualRechargeReceivedAmt.setSaleActivityCom(saleActivityCom);
            }
            settlementonlyactualRechargeReceivedAmt.setCreateName(user.getUserName());
            if (classSettlement.getClassStartTime() != null) {
                settlementonlyactualRechargeReceivedAmt.setClassStartTime(classSettlement.getClassStartTime());
            }
            settlementonlyactualRechargeReceivedAmt.setClassEndTime(classSettlement.getClassEndTime());
            settlementonlyactualRechargeReceivedAmt.setNote(classSettlement.getNote());
            classSettlementService.insertClassSettlement(settlementonlyactualRechargeReceivedAmt);
        }
        for (ClassSettlement settlement : classSettlements) {
            settlement.setCreateName(user.getUserName());
            settlement.setCreateUser(Long.valueOf(user.getUserId()));
            settlement.setEquipmentCode("PC");
            settlement.setClassNo(no);
            if (startAndEndMap.get("isRepairClass") != null && startAndEndMap.get("isRepairClass").toString().equals("2")) {
                settlement.setIsRepairClass(2);

            }else{
                settlement.setIsRepairClass(1);
            }

            settlement.setClassesDayOrNight(classesDayOrNight);
            if (classSettlement.getClassStartTime() != null) {
                settlement.setClassStartTime(classSettlement.getClassStartTime());
            }
            settlement.setClassEndTime(classSettlement.getClassEndTime());
            settlement.setNote(classSettlement.getNote());
            settlement.setClassNo(no);
            classSettlementService.insertClassSettlement(settlement);

        }
        //        无数据新增0班结 缺少新增字段
        if (classSettlements.size() == 0) {
            ClassSettlement settlement = new ClassSettlement();
            settlement.setCreateName(user.getUserName());
            settlement.setCreateUser(Long.valueOf(user.getUserId()));
            settlement.setClassNo(no);
            settlement.setClassesDayOrNight(classesDayOrNight);
            settlement.setStationId(stationId.longValue());
            if (startAndEndMap.get("isRepairClass") != null && startAndEndMap.get("isRepairClass").toString().equals("2")) {
                settlement.setIsRepairClass(2);

            }else{
                settlement.setIsRepairClass(1);
            }
            settlement.setStationName(station.getStationName());
            if (classSettlement.getClassStartTime() != null) {
                settlement.setClassStartTime(classSettlement.getClassStartTime());
            }
            settlement.setClassEndTime(classSettlement.getClassEndTime());
            settlement.setNote(classSettlement.getNote());
            classSettlementService.insertClassSettlement(settlement);
        }
        for (ClassSettlementCard settlement : classSettlementCards) {
            settlement.setCreateName(user.getUserName());
            settlement.setCreateUser(Long.valueOf(user.getUserId()));
            settlement.setEquipmentCode("PC");
            settlement.setCreateTime(new Date());
            if (classSettlement.getClassStartTime() != null) {
                settlement.setClassStartTime(classSettlement.getClassStartTime());
            }
            settlement.setClassEndTime(classSettlement.getClassEndTime());
            // settlement.setEnterpriseId(Long.valueOf(user.getEnterpriseId()));
            settlement.setNote(classSettlement.getNote());
            settlement.setClassNo(no);
            if (settlement.getClassEndTime() != null) {
                classSettlementCardService.insertClassSettlementCard(settlement);
            }

        }
        classSettlementService.insertBusinessDailyReportAsync(classSettlement.getStationId(),1,no,classSettlement.getClassEndTime(),classSettlement.getClassStartTime());
        ClassSettlement pushClass = new ClassSettlement();
        pushClass.setClassNo(no);
        pushClass.setStationId(classSettlement.getStationId());
        pushClass.setClassEndTime(classSettlement.getClassEndTime());
        if (classSettlement.getClassStartTime() != null) {
            pushClass.setClassStartTime(classSettlement.getClassStartTime());
        }

        resultMap.put("classNo", no);
        log.info("pushClass{}",pushClass);

        return AjaxResult.success(resultMap);
    }







    private CardClassSettDto countCardSett(List<ClassSettlementCard> settlementCardList){
        Map<CardRecordType,ClassSettlementCard> map = new HashMap<>();
        // 根据payType进行分组统计
        for (ClassSettlementCard settlementCard : settlementCardList) {
            if (!StringUtils.equals("dzk",settlementCard.getRechargeType())) {
                continue;
            }
            CardRecordType payType = CardRecordType.getByKey(settlementCard.getPayType(),CardRecordType.CONSUME);
            ClassSettlementCard settlement = map.get(payType);
            if (settlement == null) {
                settlement = new ClassSettlementCard();
                settlement.setPayType(payType.getKey());
                settlement.setAmt(BigDecimal.ZERO);
                settlement.setOrderCount(0L);
                settlement.setServiceCharge(BigDecimal.ZERO);
                settlement.setGiveAmt(BigDecimal.ZERO);
                map.put(payType,settlement);
            }
            settlement.setAmt(MathUtil.add(settlement.getAmt(),settlementCard.getAmt()));
            settlement.setOrderCount(MathUtil.add(settlement.getOrderCount(),settlementCard.getOrderCount()));
            settlement.setServiceCharge(MathUtil.add(settlement.getServiceCharge(),settlementCard.getServiceCharge()==null?null:settlementCard.getServiceCharge().setScale(2,RoundingMode.HALF_UP)));
            settlement.setGiveAmt(MathUtil.add(settlement.getGiveAmt(),settlementCard.getGiveAmt()));
        }
        CardClassSettDto settDto = new CardClassSettDto();// 每个payType数据相加的总计
        settDto.setTotalAmt(BigDecimal.ZERO);
        settDto.setTotalRechargeAmt(BigDecimal.ZERO);
        settDto.setTotalGiveAmt(BigDecimal.ZERO);
        settDto.setTotalWithdrawalAmount(BigDecimal.ZERO);
        settDto.setTotalRefundAmt(BigDecimal.ZERO);
        settDto.setTotalServiceCharge(BigDecimal.ZERO);
        ArrayList<ClassSettlementCard> settList = new ArrayList<>(); // 包含所有payType数据的列表
        // 遍历所有的payType,添加map中没有的类型，并进行总计
        for (CardRecordType value : CardRecordType.values()) {
            ClassSettlementCard settlement = map.get(value);
            if (settlement == null) {
                settlement = new ClassSettlementCard();
                settlement.setPayType(value.getKey());
                settlement.setAmt(BigDecimal.ZERO);
                settlement.setOrderCount(0L);
                settlement.setServiceCharge(BigDecimal.ZERO);
                settlement.setGiveAmt(BigDecimal.ZERO);
                settlement.setWithdrawalAmount(BigDecimal.ZERO);
            }
            settList.add(settlement);
            settDto.setTotalOrderCount((int) (settDto.getTotalOrderCount()+ settlement.getOrderCount()));
            switch (value){
//                case MANUAL_ADD:
//                    settDto.setTotalAmt(settDto.getTotalAmt().add(settlement.getAmt()));
//                    break;
//                case MANUAL_SUB:
//                    settlement.setAmt(settlement.getAmt().negate());
//                    settDto.setTotalAmt(settDto.getTotalAmt().add(settlement.getAmt()));
//                    break;
                case MANUAL_ADD:
                    settDto.setAllAmt(settDto.getTotalAmt().add(settlement.getAmt()));

                    break;
                case MANUAL_SUB:
                    settDto.setAllAmt(settDto.getTotalAmt().subtract(settlement.getAmt()));
                    break;
                case POS_RECHARGE:
                case WX_RECHARGE:
                    settDto.setAllAmt(settDto.getTotalAmt().add(settlement.getAmt()));
                    settDto.setTotalAmt(settDto.getTotalAmt().add(settlement.getAmt()));
                    settDto.setTotalGiveAmt(settDto.getTotalGiveAmt().add(settlement.getGiveAmt()));
                    settlement.setWithdrawalAmount(settlement.getAmt().subtract(settlement.getServiceCharge())); // 充值提现=实收-渠道费
                    settDto.setTotalWithdrawalAmount(settDto.getTotalWithdrawalAmount().add(settlement.getWithdrawalAmount()));
                    settDto.setTotalRechargeAmt(settDto.getTotalRechargeAmt().add(settlement.getAmt()));
                    settDto.setTotalServiceCharge(settDto.getTotalServiceCharge().add(settlement.getServiceCharge()));
                    settDto.setAmt(settlement.getAmt());
                    settDto.setOrderCount(settlement.getOrderCount());
                    break;
//                case CONSUME:
//                    settlement.setAmt(settlement.getAmt().negate());
//                    settDto.setTotalAmt(settDto.getTotalAmt().add(settlement.getAmt()));
//                    break;
                case REFUND:
                    settDto.setAllAmt(settDto.getTotalAmt().subtract(settlement.getAmt()));
                    settDto.setTotalAmt(settDto.getTotalAmt().subtract(settlement.getAmt()));
                    settDto.setTotalRefundAmt(settDto.getTotalRefundAmt().add(settlement.getAmt()));
                    settDto.setTotalGiveAmt(MathUtil.subtract(settDto.getTotalGiveAmt(),settlement.getGiveAmt()));
                    settlement.setWithdrawalAmount(settlement.getServiceCharge().subtract(settlement.getAmt())); // 退款提现=-(实收-渠道费)，总提现要加上这个值
                    settDto.setTotalWithdrawalAmount(settDto.getTotalWithdrawalAmount().add(settlement.getWithdrawalAmount()));
                    settDto.setTotalServiceCharge(MathUtil.subtract(settDto.getTotalServiceCharge(),settlement.getServiceCharge()));
                    //settlement.setAmt(settlement.getAmt().negate());
                    break;
            }
        }
        ClassSettlementCard wxRefund = newEmptyInstant(CardRecordType.WX_REFUND.getKey());
        ClassSettlementCard posRefund = newEmptyInstant(CardRecordType.POS_REFUND.getKey());
        if (!settlementCardList.isEmpty()) {
            ClassSettlementCard one = settlementCardList.get(0);
            Date startTime = one.getClassStartTime();
            Date endTime = one.getClassEndTime();
            Long stationId = one.getStationId();
            if (stationId != null && endTime != null) {
                List<ClassSettlementCard> refundList = classSettlementCardService.sumDzkRechargeRefund(stationId, startTime, endTime);
                for (ClassSettlementCard card : refundList) {
                    if (StringUtils.equals(card.getPayType(), CardRecordType.WX_RECHARGE.getKey())) {
                        wxRefund = card;
                        wxRefund.setPayType(CardRecordType.WX_REFUND.getKey());
                    }else if (StringUtils.equals(card.getPayType(), CardRecordType.POS_RECHARGE.getKey())) {
                        posRefund = card;
                        posRefund.setPayType(CardRecordType.POS_REFUND.getKey());
                    }
                }
            }
        }
        settList.add(wxRefund);
        settList.add(posRefund);
        settDto.setSettlementCardList(settList);
        return settDto;
    }

    private ClassSettlementCard newEmptyInstant(String payType){
        ClassSettlementCard settlementCard = new ClassSettlementCard();
        settlementCard.setPayType(payType);
        settlementCard.setAmt(BigDecimal.ZERO);
        settlementCard.setGiveAmt(BigDecimal.ZERO);
        settlementCard.setServiceCharge(BigDecimal.ZERO);
        settlementCard.setOrderCount(0L);
        return settlementCard;
    }


    /**
     * 班结
     */
    @GetMapping("/exportClassSe")
    public AjaxResult exportClassSe(ClassSettlement classSettlement) {
        return classSettlementPrintService.exportClassSe(classSettlement);
    }

    /**
     * 获取班结打印
     */
    @PostMapping("/anony/getClassSettlementPrintInfo")
    public AjaxResult getClassSettlementPrintInfo(@RequestBody ClassSettlement classSettlement) {
        return classSettlementPrintService.getClassSettlementPrintInfo(classSettlement);
    }


    /**
     * 获取班结打印
     */
    @PostMapping("/anony/getPOSClassSettlementInfo")
    public AjaxResult getPOSClassSettlementInfo(@RequestBody ClassSettlement classSettlement) {
        return classSettlementPrintService.getPOSClassSettlementInfo(classSettlement);
    }





    // 打印的班结小票的排版
    public void feiePush(List<ClassSettlement> sumClassList, List<ClassSettlement> sumOilList, List<ClassSettlement> sumPayTypeList, List<ClassSettlementCard> sumCzList, List<Map<String, Object>> oilPersonList, ClassSettlementCard czClass,ClassSettlement classSettlement, List<ClassSettlement> refundSummary,List<Map<String, Object>> listDetail4User,List<ClassSettlementCard> transactionSummary) { //
        try {
            if (sumClassList == null || sumClassList.size() <= 0) {
                return;
            }
            Station station = stationService.selectStationById(sumClassList.get(0).getStationId());

            StationDeviceManage stationDeviceManage = new StationDeviceManage();
            stationDeviceManage.setStationId(sumClassList.get(0).getStationId());
            stationDeviceManage.setDeviceType("3");
            List<StationDeviceManage> stationDeviceManages = stationDeviceManageService.selectStationDeviceManageList(stationDeviceManage);
            if (stationDeviceManages == null || stationDeviceManages.size() <= 0) {
                return;
            }
            StringBuilder content = new StringBuilder();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (true) {
                content.append("<BOLD><B>--班结小票----</B></BOLD><BR>");
                if (sumClassList.get(0).getClassStartTime() != null) {
                    content.append("接班时间：" + sdf.format(sumClassList.get(0).getClassStartTime()) + "<BR>");
                } else {
                    content.append("接班时间：" + "首次" + "<BR>");
                }
                if (sumClassList.get(0).getClassEndTime() != null) {
                    content.append("交班时间：" + sdf.format(sumClassList.get(0).getClassEndTime()) + "<BR>");
                }
                content.append("班结人："+ sumClassList.get(0).getCreateName() + "<BR>");
                content.append("---------------------------"+ "<BR>");


                if (CollectionUtils.isNotEmpty(sumClassList)) {
                    BigDecimal receivableAmt  = sumClassList.get(0).getReceivableAmt()!=null?sumClassList.get(0).getReceivableAmt():BigDecimal.ZERO;
                    content.append("消费应收总金额：" +receivableAmt + "元<BR>");
                }


                if (sumClassList.get(0).getDiscountAmt() != null) {
                    BigDecimal discountAmountAmt =  Objects.isNull(sumClassList.get(0).getDiscountAmt()) ? BigDecimal.ZERO : sumClassList.get(0).getDiscountAmt();
                    BigDecimal discountCouponAmt =  Objects.isNull(sumClassList.get(0).getDiscountCouponAmt()) ? BigDecimal.ZERO : sumClassList.get(0).getDiscountCouponAmt();
                    content.append("消费优惠金额：" + discountAmountAmt.add(discountCouponAmt) + "元<BR>");
                }

                if (sumClassList.get(0).getReceivableAmt() != null) {
                    content.append("消费实收总金额：" + sumClassList.get(0).getAmt() + "元<BR>");
                }

                if (CollectionUtils.isNotEmpty(refundSummary)) {
                    BigDecimal refundSum = refundSummary.stream().filter(m -> !"合计".equals(m.getPayType())).map(ClassSettlement::getRefundAmt).reduce(BigDecimal.ZERO, BigDecimal::add);

                    //充值退款
                    BigDecimal refRefoundSum = refundSummary.stream().filter(m -> !"合计".equals(m.getPayType()) && "ref".equals(m.getPayType())).map(ClassSettlement::getRefundAmt).reduce(BigDecimal.ZERO, BigDecimal::add);
                    //消费退款
                    BigDecimal consumeRefoundSum = refundSum.subtract(refRefoundSum);
                    //充值退款

                    content.append("退款总金额:(消费退款+充值退款):<BR>" + "(" + consumeRefoundSum + "+" + refRefoundSum + ")" + refundSum  + "元<BR>");
                }

                //平台储值合计
//                if(!CollectionUtils.isEmpty(sumCzList)){
                    content.append("平台储值合计（电子卡+实体卡+车队卡）：" );
                    BigDecimal dzkAmk = BigDecimal.ZERO;
                    BigDecimal dkqAmt = BigDecimal.ZERO;
                    BigDecimal cdkAmt = BigDecimal.ZERO;
                    //电子卡手动充值金额
                    BigDecimal handRecharge = BigDecimal.ZERO;
                    for (ClassSettlementCard classSettlementCard : transactionSummary) {
                        if(RechargeTypeEnum.imp.getType().equals(classSettlementCard.getPayType())){
                            handRecharge = handRecharge.add(Objects.isNull(classSettlementCard.getAmt()) ? BigDecimal.ZERO : classSettlementCard.getAmt());
                        }
                        if(RechargeTypeEnum.pos.getType().equals(classSettlementCard.getPayType())){
                            handRecharge = handRecharge.add(Objects.isNull(classSettlementCard.getAmt()) ? BigDecimal.ZERO : classSettlementCard.getAmt());
                        }
                        if(RechargeTypeEnum.wx.getType().equals(classSettlementCard.getPayType())){
                            handRecharge = handRecharge.add(Objects.isNull(classSettlementCard.getAmt()) ? BigDecimal.ZERO : classSettlementCard.getAmt());
                        }
                    }

                //车队卡储值
                BigDecimal handCdkRecharge = BigDecimal.ZERO;
                for (ClassSettlementCard classSettlementCard : transactionSummary) {
                    if(RechargeTypeEnum.cdk.getType().equals(classSettlementCard.getPayType())){
                        handCdkRecharge = Objects.isNull(classSettlementCard.getAmt()) ? BigDecimal.ZERO : classSettlementCard.getAmt();
                    }
                }

                BigDecimal handDkqRecharge = BigDecimal.ZERO;
                for (ClassSettlementCard classSettlementCard : transactionSummary) {
                    if(RechargeTypeEnum.dkq.getType().equals(classSettlementCard.getPayType())){
                        handDkqRecharge = Objects.isNull(classSettlementCard.getAmt()) ? BigDecimal.ZERO : classSettlementCard.getAmt();
                    }
                }
                dzkAmk = handRecharge;
                    for (ClassSettlementCard classSettlementCard : sumCzList) {
                        if(StringUtils.isEmpty(classSettlementCard.getRechargeType())){
                            continue;
                        }
                        String des = "";
                        if(!StringUtils.isEmpty(classSettlementCard.getRechargeType())){
                           if (PayTypeEnum.dkq == PayTypeEnum.getByType(classSettlementCard.getRechargeType())) {
                                dkqAmt =  classSettlementCard.getAmt();
                            } else if(PayTypeEnum.cdk == PayTypeEnum.getByType(classSettlementCard.getRechargeType())){
                                cdkAmt =  classSettlementCard.getAmt();
                            }
                        }

//                        content.append(des + "     " + classSettlementCard.getOrderCount() + "     " + classSettlementCard.getAmt() + "<BR>");

                    }
                content.append( "(" + dzkAmk + "元 + " + handDkqRecharge + "元 + " + handCdkRecharge + "元)" + dzkAmk.add(handDkqRecharge).add(handCdkRecharge) + ("元") + "<BR>");
//                }
                BigDecimal sumOrderCount = sumOilList.stream().filter(cs -> Objects.nonNull(cs.getOrderLiters())).map(ClassSettlement::getOrderLiters).reduce(BigDecimal.ZERO, BigDecimal::add);
                content.append("合计销售数量：" + sumOrderCount + "L/kg<BR>");

                BigDecimal consumeReceived  = Objects.isNull(sumClassList.get(0).getAmt()) ? BigDecimal.ZERO : sumClassList.get(0).getAmt();
                BigDecimal actualRechargeReceivedAmt = Objects.isNull(sumClassList.get(0).getActualRechargeReceivedAmt()) ? BigDecimal.ZERO : sumClassList.get(0).getActualRechargeReceivedAmt();

//                content.append("到账总金额：" + consumeReceived.add(actualRechargeReceivedAmt)  + "元<BR>");
                content.append("到账总金额：" + sumClassList.get(0).getTotalWithdrawalAmount().setScale(2, RoundingMode.HALF_DOWN) + "元<BR>");


                content.append("--------------------------" + "<BR>");
                content.append("收款明细" + "<BR>");
                content.append("支付方式   笔数    数量(L/kg)     金额(元)" + "<BR>");
                for (ClassSettlement classSettlement1 : sumPayTypeList) {
                    if(StringUtils.isEmpty(classSettlement1.getPayType())){
                        continue;
                    }
                    String  desTxt = PayTypeEnum.getByType(classSettlement1.getPayType())!=null?PayTypeEnum.getByType(classSettlement1.getPayType()).getDes():classSettlement1.getPayType();
                    content.append(desTxt + "    " + classSettlement1.getOrderCount() + "     " + classSettlement1.getOrderLiters() + "    " + classSettlement1.getAmt() + "<BR>");
                }
                content.append("--------------------------" + "<BR>");
                content.append("充值汇总" + "<BR>");
                content.append("充值类型   笔数   金额(元)" + "<BR>");
                if(!CollectionUtils.isEmpty(transactionSummary)){
                    for (ClassSettlementCard classSettlementCard : transactionSummary) {
                        if("合计".equals(classSettlementCard.getPayType().toString()) || Objects.isNull(classSettlementCard.getAmt()) || BigDecimal.ZERO.compareTo(classSettlementCard.getAmt()) == 0){
                            continue;
                        }
                        BigDecimal rechargeAmt = Objects.nonNull(classSettlementCard.getAmt()) ? classSettlementCard.getAmt() : BigDecimal.ZERO;
                        content.append(RechargeTypeEnum.getByType(classSettlementCard.getPayType()).getDes() + "     " + classSettlementCard.getOrderCount() + "     " + rechargeAmt.toString() + "<BR>");
                    }
                }


                content.append("--------------------------" + "<BR>");
                content.append("油品汇总" + "<BR>");

                content.append("油品   笔数    数量(L/kg)   金额(元)" + "<BR>");


                for (ClassSettlement classSettlement1 : sumOilList) {
                    if(StringUtils.isEmpty(classSettlement1.getOilName())){
                        continue;
                    }
                    content.append(classSettlement1.getOilName() + "     " + classSettlement1.getOrderCount() + "     " + classSettlement1.getOrderLiters() + "    " + classSettlement1.getAmt() + "<BR>");
                }
                content.append("--------------------------" + "<BR>");
                content.append("员工汇总" + "<BR>");
                content.append("员工名称   笔数   金额(元)" + "<BR>");

                //员工汇总
                // 根据活动分组查询统计信息
                Map<String, List<Map<String, Object>>> oilPersonnelNameMap = listDetail4User.stream().filter(m -> !"合计".equals(m.get("oil_personnel_name"))).collect(Collectors.groupingBy((m -> (String) m.get("oil_personnel_name"))));
                for (Map.Entry<String, List<Map<String, Object>>> entry : oilPersonnelNameMap.entrySet()) {
                    String oilPersonnelName = entry.getKey();
                    List<Map<String, Object>> value = entry.getValue();
                    //笔数
                    Integer orderCount = value.stream().mapToInt(map -> ((Number) map.get("order_count")).intValue()).sum();
                    //金额
                    Double amt = value.stream().mapToDouble(map -> ((Number) map.get("amt")).doubleValue()).sum();
                    content.append(oilPersonnelName + "       " + orderCount + "       " + new BigDecimal(amt).setScale(2,RoundingMode.HALF_DOWN) + "<BR>");
                }

//                if (sumClassList.get(0).getOrderCount() != null) {
//                    content.append("小票张数：" + sumClassList.get(0).getOrderCount() + "<BR>");
//                }


//                if (sumClassList.get(0).getAmt() != null) {
//                    content.append("订单实收金额：" + sumClassList.get(0).getAmt() + "<BR>");
//                }
//                if (czClass != null && czClass.getAmt() != null) {
//                    content.append("充值金额：" + czClass.getAmt() + "<BR>");
//                }

//                if( czClass!=null&&czClass.getAmt() != null&&sumClassList.get(0).getAmt()!=null){
//                    content.append("订单充值合计：" + sumClassList.get(0).getAmt().add(czClass.getAmt())+ "<BR>");
//                }else if(sumClassList.get(0).getAmt()!=null) {
//                    content.append("订单充值合计：" + sumClassList.get(0).getAmt()+ "<BR>");
//                }else if(czClass!=null&&czClass.getAmt()!=null){
//                    content.append("订单充值合计：" + czClass.getAmt()+ "<BR>");
//                }


                content.append("-------------------------<BR>");
                content.append("打印时间： " + DateUtil.now() + "<BR>");
                content.append("<BR>");
                content.append("<BR>");
                content.append("<BR>");
                Boolean personFlage = false;
                if (station != null && station.getClassPersonFlag() != null && station.getClassPersonFlag().equals("1")) {
                    for (Map<String, Object> oilPerson : oilPersonList) {
                        content.append("<BOLD><B>-班结小票---" + oilPerson.get("oilPersonnelName") + "-</B></BOLD><BR>");
                        if (sumClassList.get(0).getClassStartTime() != null) {
                            content.append("开始时间：" + sdf.format(sumClassList.get(0).getClassStartTime()) + "<BR>");
                        } else {
                            content.append("开始时间：" + "首次" + "<BR>");
                        }
                        if (sumClassList.get(0).getClassEndTime() != null) {
                            content.append("结束时间：" + sdf.format(sumClassList.get(0).getClassEndTime()) + "<BR>");
                        }
                        content.append("油品   笔数    升数     金额" + "<BR>");
                        content.append("--------------------------" + "<BR>");
                        List<ClassSettlement> oilList = (List<ClassSettlement>) oilPerson.get("oilList");
                        for (ClassSettlement classSettlement1 : oilList) {
                            content.append(classSettlement1.getOilName() + "   " + classSettlement1.getOrderCount() + "    " + classSettlement1.getOrderLiters() + "    " + classSettlement1.getAmt() + "<BR>");
                        }
                        content.append("--------------------------" + "<BR>");
                        if (oilPerson.get("orderCount") != null) {
                            content.append("小票张数：" + oilPerson.get("orderCount") + "<BR>");
                        }

                        if (oilPerson.get("receivableAmt") != null) {
                            content.append("消费金额：" + oilPerson.get("receivableAmt") + "<BR>");
                        }
                        if (oilPerson.get("discountAmt") != null) {
                            content.append("优惠金额：" + oilPerson.get("discountAmt") + "<BR>");
                        }

                        if (oilPerson.get("refundAmt") != null) {
                            content.append("退款金额：" + oilPerson.get("refundAmt") + "<BR>");
                        }
                        if (oilPerson.get("amt") != null) {
                            content.append("订单实际支付金额：" + oilPerson.get("amt") + "<BR>");
                        }
                        content.append("<BR>");
                        content.append("<BR>");
                    }
                }
            }
            content.append("<BR>");
            content.append("<BR>");
            StationDeviceManage stationDevice = stationDeviceManages.get(0);
            String deviceFactory = stationDevice.getDeviceFactory();

            PrintEnum printEnum = PrintEnum.getByCode(deviceFactory);
            switch (printEnum){
                case YILIANYUNK4:
                    String audiok4 = "<VN>8</VN>";

                    String ylyContentk4 = content.toString().replace("<BR>", "\r\n").replace("</B></BOLD>","").replace("<BOLD><B>","");
                    //初始化控制器类
                    Methods mk4= Methods.getInstance();
                    Object tokenk4 = redisCache.getCacheObject("STATION:DEVICE:" + stationDevice.getClientId());

                    Integer random6k4 = (int) ((Math.random() * 9 + 1) * 100000);

                    if(Objects.nonNull(tokenk4)){
                        String printk4 = mk4.print(stationDevice.getDeviceNo(),audiok4 + ylyContentk4.toString(), random6k4.toString());
                        log.info("小票机返回值{}",printk4);
                        JSONObject json = new JSONObject(printk4);
                        if("0".equals(json.getString("error"))){
                            break;
                        }
                    }

                    //初始化终端信息
                    mk4.init(stationDevice.getClientId(), stationDevice.getClientSecret());
                    //获取token
                    String refreshTokenK4 = mk4.getFreedomToken();
                    //存入redis
                    redisCache.setCacheObject("STATION:DEVICE:" + stationDevice.getClientId(),refreshTokenK4,30, TimeUnit.DAYS);


                    String printk4 = mk4.print(stationDevice.getDeviceNo(), audiok4 + ylyContentk4, random6k4.toString());
                    log.info("小票机返回值2{}",printk4);
                    break;

                case YILIANYUN:
                    String audio = "<audio>班结信息已打印</audio>";

                    String ylyContent = content.toString().replace("<BR>", "\r\n").replace("</B></BOLD>","").replace("<BOLD><B>","");
                    //初始化控制器类
                    Methods m= Methods.getInstance();
                    Object token = redisCache.getCacheObject("STATION:DEVICE:" + stationDevice.getClientId());

                    Integer random6 = (int) ((Math.random() * 9 + 1) * 100000);

                    if(Objects.nonNull(token)){
                        String print = m.print(stationDevice.getDeviceNo(),audio + ylyContent.toString(), random6.toString());
                        log.info("小票机返回值{}",print);
                        JSONObject json = new JSONObject(print);
                        if("0".equals(json.getString("error"))){
                            break;
                        }
                    }

                    //初始化终端信息
                    m.init(stationDevice.getClientId(), stationDevice.getClientSecret());
                    //获取token
                    String refreshToken = m.getFreedomToken();
                    //存入redis
                    redisCache.setCacheObject("STATION:DEVICE:" + stationDevice.getClientId(),refreshToken,30, TimeUnit.DAYS);


                    String print = m.print(stationDevice.getDeviceNo(), audio + ylyContent, random6.toString());
                    log.info("小票机返回值2{}",print);
                    break;
                case FEIE:
                    FeiEPrinterUtil.printReceipt(stationDeviceManages.get(0).getDeviceNo(), content.toString());
                    break;
            }
            //修改小票打印状态
            classSettlementService.updateClassSettlementPrintStatus(classSettlement.getClassNo());

            return;
        } catch (Exception e) {
            logger.error(">pushConsumeToUser", e);
            return;
        }

    }

    public AjaxResult feiePushRePrint(List<ClassSettlement> sumClassList, List<ClassSettlement> sumOilList, List<ClassSettlement> sumPayTypeList, List<ClassSettlementCard> sumCzList, List<Map<String, Object>> oilPersonList, ClassSettlementCard czClass,ClassSettlement classSettlement,List<ClassSettlement> refundSummary,List<Map<String, Object>> listDetail4User,List<ClassSettlementCard> transactionSummary, List<ClassSettlementCard> queryGroupByRecharge) { //
        try {
            if (sumClassList == null || sumClassList.size() <= 0) {
                return AjaxResult.error("补打失败");
            }
            Station station = stationService.selectStationById(sumClassList.get(0).getStationId());

            StationDeviceManage stationDeviceManage = new StationDeviceManage();
            stationDeviceManage.setStationId(sumClassList.get(0).getStationId());
            stationDeviceManage.setDeviceType("3");
            List<StationDeviceManage> stationDeviceManages = stationDeviceManageService.selectStationDeviceManageList(stationDeviceManage);
            if (stationDeviceManages == null || stationDeviceManages.size() <= 0) {
                return AjaxResult.error("当前站点没有打印机");
            }
            StringBuilder content = new StringBuilder();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Map<String, Object> baseSetting = new HashMap<>(); // 基础设置

            baseSetting.put("stationName", "芝麻香油站"); //油站名称
            baseSetting.put("successioDate", sdf.format(sumClassList.get(0).getClassStartTime())); // 接班时间
            baseSetting.put("shiftDate", "2023-09-13 19:59:43"); // 交班时间
            baseSetting.put("submitter", "靓仔！"); // 交接人
            if (true) {
                content.append("<BOLD><B>班结小票----补打</B></BOLD><BR>");
                if (sumClassList.get(0).getClassStartTime() != null) {
                    baseSetting.put("successioDate", sdf.format(sumClassList.get(0).getClassStartTime())); // 接班时间
//                    content.append("接班时间：" + sdf.format(sumClassList.get(0).getClassStartTime()) + "<BR>");
                } else {
//                    content.append("接班时间：" + "首次" + "<BR>");
                    baseSetting.put("successioDate", "首次"); // 接班时间
                }
                if (sumClassList.get(0).getClassEndTime() != null) {
//                    content.append("交班时间：" + sdf.format(sumClassList.get(0).getClassEndTime()) + "<BR>");
                    baseSetting.put("shiftDate", sdf.format(sumClassList.get(0).getClassEndTime())); // 交班时间
                }
//                content.append("班结人："+ sumClassList.get(0).getCreateName() + "<BR>");
                baseSetting.put("submitter", sumClassList.get(0).getCreateName()); // 交接人
//                content.append("---------------------------"+ "<BR>");
                Map<String, Object> totalSum = new HashMap<>(); // 合计汇总
                totalSum.put("receivableAmt", 20200.33); // 消费应收总金额
                totalSum.put("discountAmt", 2020.33);// 消费优惠总金额
                totalSum.put("receivedAmt", 2020.33);// 消费实收总金额
                totalSum.put("consumptionRefundAmt", 101.12);// 消费退款
                totalSum.put("rechargeRefundAmt", 101.21);// 充值退款
                totalSum.put("refundAmt", 202.33);// 退款总金额
                totalSum.put("dzkSavingsAtm", 36473.66);// 电子卡储值额
                totalSum.put("hykSavingsAtm", 3748.33);// 实体卡储值额
                totalSum.put("cdkSavingsAtm", 8372.22);// 车队卡储值额
                totalSum.put("savingsAtm", 48594.21);// 储值合计
                totalSum.put("salesVolume", 7878.26);// 销售量(L/KG)
                totalSum.put("salesQty", 177);// 销售笔数
                totalSum.put("arrivalAmt", 50392.33);// 到账总金额
                totalSum.put("arrivalQty", 177);// 到账笔数

                if (CollectionUtils.isNotEmpty(sumClassList)) {
                    BigDecimal receivableAmt  = sumClassList.get(0).getReceivableAmt()!=null?sumClassList.get(0).getReceivableAmt():BigDecimal.ZERO;
//                    content.append("消费应收总金额：" +receivableAmt + "元<BR>");
                    totalSum.put("receivableAmt", receivableAmt); // 消费应收总金额
                }


                if (sumClassList.get(0).getDiscountAmt() != null) {
                    BigDecimal discountAmountAmt =  Objects.isNull(sumClassList.get(0).getDiscountAmt()) ? BigDecimal.ZERO : sumClassList.get(0).getDiscountAmt();
                    BigDecimal discountCouponAmt =  Objects.isNull(sumClassList.get(0).getDiscountCouponAmt()) ? BigDecimal.ZERO : sumClassList.get(0).getDiscountCouponAmt();
                    content.append("消费优惠金额：" + discountAmountAmt.add(discountCouponAmt) + "元<BR>");
                    totalSum.put("discountAmt", discountAmountAmt.add(discountCouponAmt));// 消费优惠总金额
                }

                if (sumClassList.get(0).getReceivableAmt() != null) {
                    content.append("消费实收总金额：" + sumClassList.get(0).getAmt() + "元<BR>");
                    totalSum.put("receivedAmt", sumClassList.get(0).getAmt());// 消费实收总金额
                }

                if (CollectionUtils.isNotEmpty(refundSummary)) {
                    BigDecimal refundSum = refundSummary.stream().filter(m -> !"合计".equals(m.getPayType())).map(ClassSettlement::getRefundAmt).reduce(BigDecimal.ZERO, BigDecimal::add);

                    //充值退款
                    BigDecimal refRefoundSum = refundSummary.stream().filter(m -> !"合计".equals(m.getPayType()) && "ref".equals(m.getPayType())).map(ClassSettlement::getRefundAmt).reduce(BigDecimal.ZERO, BigDecimal::add);
                    //消费退款
                    BigDecimal consumeRefoundSum = refundSum.subtract(refRefoundSum);
                    //充值退款
                    totalSum.put("consumptionRefundAmt",consumeRefoundSum);// 消费消费退款
                    totalSum.put("rechargeRefundAmt", refRefoundSum);// 充值退款
                    totalSum.put("refundAmt", refundSum);// 退款总金额
                    content.append("退款总金额:(消费退款+充值退款):<BR>" + "(" + consumeRefoundSum + "+" + refRefoundSum + ")" + refundSum  + "元<BR>");
                }

                //平台储值合计
//                if(!CollectionUtils.isEmpty(sumCzList)){
                    content.append("平台储值合计（电子卡+实体卡+车队卡）：" );
                    BigDecimal dzkAmk = BigDecimal.ZERO;
                    BigDecimal dkqAmt = BigDecimal.ZERO;
                    BigDecimal cdkAmt = BigDecimal.ZERO;
                    //电子卡手动充值金额
                    BigDecimal handRecharge = BigDecimal.ZERO;
                    for (ClassSettlementCard classSettlementCard : transactionSummary) {
                        if(RechargeTypeEnum.imp.getType().equals(classSettlementCard.getPayType())){
                            handRecharge = handRecharge.add(Objects.isNull(classSettlementCard.getAmt()) ? BigDecimal.ZERO : classSettlementCard.getAmt());
                        }
                        if(RechargeTypeEnum.pos.getType().equals(classSettlementCard.getPayType())){
                            handRecharge = handRecharge.add(Objects.isNull(classSettlementCard.getAmt()) ? BigDecimal.ZERO : classSettlementCard.getAmt());
                        }
                        if(RechargeTypeEnum.wx.getType().equals(classSettlementCard.getPayType())){
                            handRecharge = handRecharge.add(Objects.isNull(classSettlementCard.getAmt()) ? BigDecimal.ZERO : classSettlementCard.getAmt());
                        }
                    }

                    //车队卡储值
                    BigDecimal handCdkRecharge = BigDecimal.ZERO;
                    for (ClassSettlementCard classSettlementCard : transactionSummary) {
                        if(RechargeTypeEnum.cdk.getType().equals(classSettlementCard.getPayType())){
                            handCdkRecharge = Objects.isNull(classSettlementCard.getAmt()) ? BigDecimal.ZERO : classSettlementCard.getAmt();
                        }
                    }

                    BigDecimal handDkqRecharge = BigDecimal.ZERO;
                    for (ClassSettlementCard classSettlementCard : transactionSummary) {
                        if(RechargeTypeEnum.dkq.getType().equals(classSettlementCard.getPayType())){
                            handDkqRecharge = Objects.isNull(classSettlementCard.getAmt()) ? BigDecimal.ZERO : classSettlementCard.getAmt();
                        }
                    }

                    dzkAmk = handRecharge;
                    for (ClassSettlementCard classSettlementCard : sumCzList) {
                        if(StringUtils.isEmpty(classSettlementCard.getRechargeType())){
                            continue;
                        }
                        String des = "";
                        if(!StringUtils.isEmpty(classSettlementCard.getRechargeType())){
                             if (PayTypeEnum.dkq == PayTypeEnum.getByType(classSettlementCard.getRechargeType())) {
                                dkqAmt =  classSettlementCard.getAmt();

                            } else if(PayTypeEnum.cdk == PayTypeEnum.getByType(classSettlementCard.getRechargeType())){
                                cdkAmt =  classSettlementCard.getAmt();
                            }
                        }

//                        content.append(des + "     " + classSettlementCard.getOrderCount() + "     " + classSettlementCard.getAmt() + "<BR>");

                    }
                content.append( "(" + dzkAmk + "元 + " + handDkqRecharge + "元 + " + handCdkRecharge + "元)" + dzkAmk.add(handDkqRecharge).add(handCdkRecharge) + ("元") + "<BR>");
//                }
                BigDecimal sumOrderCount = sumOilList.stream().filter(cs -> Objects.nonNull(cs.getOrderLiters())).map(ClassSettlement::getOrderLiters).reduce(BigDecimal.ZERO, BigDecimal::add);
                content.append("合计销售数量：" + sumOrderCount + "L/kg<BR>");
                //到账总金额 = 消费合计实收 + 充值合计实收
                BigDecimal consumeReceived  = Objects.isNull(sumClassList.get(0).getAmt()) ? BigDecimal.ZERO : sumClassList.get(0).getAmt();
                BigDecimal actualRechargeReceivedAmt = Objects.isNull(sumClassList.get(0).getActualRechargeReceivedAmt()) ? BigDecimal.ZERO : sumClassList.get(0).getActualRechargeReceivedAmt();
//                content.append("到账总金额：" + consumeReceived.add(actualRechargeReceivedAmt)  + "元<BR>");
                content.append("到账总金额：" + sumClassList.get(0).getTotalWithdrawalAmount().stripTrailingZeros()  + "元<BR>");


                content.append("--------------------------" + "<BR>");
                content.append("收款明细" + "<BR>");
                content.append("支付方式    笔数     金额(元)" + "<BR>");
                for (ClassSettlement classSettlement1 : sumPayTypeList) {
                    if(StringUtils.isEmpty(classSettlement1.getPayType())){
                        continue;
                    }
                  String  desTxt = PayTypeEnum.getByType(classSettlement1.getPayType())!=null?PayTypeEnum.getByType(classSettlement1.getPayType()).getDes():classSettlement1.getPayType();
                    content.append(desTxt + "    " + padCountString(String.valueOf(classSettlement1.getOrderCount())) + "    " + classSettlement1.getAmt().setScale(2, RoundingMode.HALF_DOWN) + "<BR>");
                }
                content.append("--------------------------" + "<BR>");
                content.append("充值汇总" + "<BR>");
                content.append("充值类型    笔数     金额(元)" + "<BR>");
                if(!CollectionUtils.isEmpty(transactionSummary)){
                    for (ClassSettlementCard classSettlementCard : transactionSummary) {
                        if("合计".equals(classSettlementCard.getPayType().toString())|| Objects.isNull(classSettlementCard.getAmt()) || BigDecimal.ZERO.compareTo(classSettlementCard.getAmt()) == 0){
                            continue;
                        }
                        BigDecimal rechargeAmt = Objects.nonNull(classSettlementCard.getAmt()) ? classSettlementCard.getAmt() : BigDecimal.ZERO;
                        content.append(RechargeTypeEnum.getByType(classSettlementCard.getPayType()).getDes() + "    " + padCountString(classSettlementCard.getOrderCount().toString()) + "    " + rechargeAmt.toString() + "<BR>");
                    }
                }
                content.append("--------------------------" + "<BR>");

                content.append("会员卡-交易汇总" + "<BR>");
                content.append("消费类型    笔数     实收(元)" + "<BR>");

                if(!CollectionUtils.isEmpty(queryGroupByRecharge)){
                    for (ClassSettlementCard classSettlementCard : queryGroupByRecharge) {
                        content.append(padCountString(CardRecordType.getByKey(classSettlementCard.getPayType()).getName()) + "    " + padCountString(classSettlementCard.getOrderCount().toString()) + "    " + classSettlementCard.getAmt().toString() + "<BR>");
                    }
                }


                content.append("--------------------------" + "<BR>");
                content.append("油品汇总" + "<BR>");

                content.append("油品       笔数     金额(元)" + "<BR>");

                for (ClassSettlement classSettlement1 : sumOilList) {
                    if(StringUtils.isEmpty(classSettlement1.getOilName())){
                        continue;
                    }
                    content.append(padCountOilNameString(classSettlement1.getOilName()) + "        " + padCountString(classSettlement1.getOrderCount().toString()) + "    " + classSettlement1.getAmt() + "<BR>");
                }
                content.append("--------------------------" + "<BR>");
                content.append("员工汇总" + "<BR>");
                content.append("员工名称   笔数     金额(元)" + "<BR>");

                //员工汇总
                // 根据活动分组查询统计信息
                Map<String, List<Map<String, Object>>> oilPersonnelNameMap = listDetail4User.stream().filter(m -> !"合计".equals(m.get("oil_personnel_name"))).collect(Collectors.groupingBy((m -> (String) m.get("oil_personnel_name"))));
                for (Map.Entry<String, List<Map<String, Object>>> entry : oilPersonnelNameMap.entrySet()) {
                    String oilPersonnelName = entry.getKey();
                    List<Map<String, Object>> value = entry.getValue();
                    //笔数
                    Integer orderCount = value.stream().mapToInt(map -> ((Number) map.get("order_count")).intValue()).sum();
                    //金额
                    Double amt = value.stream().mapToDouble(map -> ((Number) map.get("amt")).doubleValue()).sum();

                    if(StringUtils.isNotBlank(oilPersonnelName) && oilPersonnelName.length() > 5){
                        oilPersonnelName = oilPersonnelName.substring(0,5);
                    }

                    content.append(padCountString(oilPersonnelName) + "      " + padCountString(orderCount.toString()) + "    " + new BigDecimal(amt).setScale(2,RoundingMode.HALF_DOWN) + "<BR>");
                }

//                if (sumClassList.get(0).getOrderCount() != null) {
//                    content.append("小票张数：" + sumClassList.get(0).getOrderCount() + "<BR>");
//                }


//                if (sumClassList.get(0).getAmt() != null) {
//                    content.append("订单实收金额：" + sumClassList.get(0).getAmt() + "<BR>");
//                }
//                if (czClass != null && czClass.getAmt() != null) {
//                    content.append("充值金额：" + czClass.getAmt() + "<BR>");
//                }

//                if( czClass!=null&&czClass.getAmt() != null&&sumClassList.get(0).getAmt()!=null){
//                    content.append("订单充值合计：" + sumClassList.get(0).getAmt().add(czClass.getAmt())+ "<BR>");
//                }else if(sumClassList.get(0).getAmt()!=null) {
//                    content.append("订单充值合计：" + sumClassList.get(0).getAmt()+ "<BR>");
//                }else if(czClass!=null&&czClass.getAmt()!=null){
//                    content.append("订单充值合计：" + czClass.getAmt()+ "<BR>");
//                }


                content.append("-------------------------<BR>");
                content.append("打印时间： " + DateUtil.now() + "<BR>");
                content.append("<BR>");
                content.append("<BR>");
                content.append("<BR>");
                Boolean personFlage = false;
                if (station != null && station.getClassPersonFlag() != null && station.getClassPersonFlag().equals("1")) {
                    for (Map<String, Object> oilPerson : oilPersonList) {
                        content.append("<BOLD><B>-班结小票---" + oilPerson.get("oilPersonnelName") + "-</B></BOLD><BR>");
                        if (sumClassList.get(0).getClassStartTime() != null) {
                            content.append("开始时间：" + sdf.format(sumClassList.get(0).getClassStartTime()) + "<BR>");
                        } else {
                            content.append("开始时间：" + "首次" + "<BR>");
                        }
                        if (sumClassList.get(0).getClassEndTime() != null) {
                            content.append("结束时间：" + sdf.format(sumClassList.get(0).getClassEndTime()) + "<BR>");
                        }
                        content.append("油品   笔数    升数     金额" + "<BR>");
                        content.append("--------------------------" + "<BR>");
                        List<ClassSettlement> oilList = (List<ClassSettlement>) oilPerson.get("oilList");
                        for (ClassSettlement classSettlement1 : oilList) {
                            content.append(classSettlement1.getOilName() + "   " + classSettlement1.getOrderCount() + "    " + classSettlement1.getOrderLiters() + "    " + classSettlement1.getAmt() + "<BR>");
                        }
                        content.append("--------------------------" + "<BR>");
                        if (oilPerson.get("orderCount") != null) {
                            content.append("小票张数：" + oilPerson.get("orderCount") + "<BR>");
                        }

                        if (oilPerson.get("receivableAmt") != null) {
                            content.append("消费金额：" + oilPerson.get("receivableAmt") + "<BR>");
                        }
                        if (oilPerson.get("discountAmt") != null) {
                            content.append("优惠金额：" + oilPerson.get("discountAmt") + "<BR>");
                        }

                        if (oilPerson.get("refundAmt") != null) {
                            content.append("退款金额：" + oilPerson.get("refundAmt") + "<BR>");
                        }
                        if (oilPerson.get("amt") != null) {
                            content.append("订单实际支付金额：" + oilPerson.get("amt") + "<BR>");
                        }
                        content.append("<BR>");
                        content.append("<BR>");
                    }
                }
            }
            content.append("<BR>");
            content.append("<BR>");
            StationDeviceManage stationDevice = stationDeviceManages.get(0);
            String deviceFactory = stationDevice.getDeviceFactory();

            PrintEnum printEnum = PrintEnum.getByCode(deviceFactory);
            String printRes = "";
            AjaxResult ajaxResult = AjaxResult.success();
            switch (printEnum){
                case YILIANYUNK4:
                    String audiok4 = "<VN>8</VN>";

                    String ylyContentk4 = content.toString().replace("<BR>", "\r\n").replace("</B></BOLD>","").replace("<BOLD><B>","");
                    //初始化控制器类
                    Methods mk4= Methods.getInstance();
                    Object tokenk4 = redisCache.getCacheObject("STATION:DEVICE:" + stationDevice.getClientId());

                    Integer random6k4 = (int) ((Math.random() * 9 + 1) * 100000);

                    if(Objects.nonNull(tokenk4)){
                        String printk4 = mk4.print(stationDevice.getDeviceNo(),audiok4 + ylyContentk4.toString(), random6k4.toString());
                        log.info("小票机返回值{}",printk4);
                        JSONObject json = new JSONObject(printk4);
                        if("0".equals(json.getString("error"))){
                            break;
                        }
                    }

                    //初始化终端信息
                    mk4.init(stationDevice.getClientId(), stationDevice.getClientSecret());
                    //获取token
                    String refreshTokenK4 = mk4.getFreedomToken();
                    //存入redis
                    redisCache.setCacheObject("STATION:DEVICE:" + stationDevice.getClientId(),refreshTokenK4,30, TimeUnit.DAYS);


                    String printk4 = mk4.print(stationDevice.getDeviceNo(), audiok4 + ylyContentk4, random6k4.toString());
                    log.info("小票机返回值2{}",printk4);
                    break;
                case YILIANYUN:
                    String audio = "<audio>班结信息已打印</audio>";

                    String ylyContent = content.toString().replace("<BR>", "\r\n").replace("</B></BOLD>","").replace("<BOLD><B>","");
                    //初始化控制器类
                    Methods m= Methods.getInstance();
                    Object token = redisCache.getCacheObject("STATION:DEVICE:" + stationDevice.getClientId());

                    Integer random6 = (int) ((Math.random() * 9 + 1) * 100000);

                    if(Objects.nonNull(token)){
                        String print = m.print(stationDevice.getDeviceNo(),audio + ylyContent.toString(), random6.toString());
                        log.info("小票机返回值{}",print);
                        JSONObject json = new JSONObject(print);
                        if("0".equals(json.getString("error"))){
                            classSettlementService.updateClassSettlementPrintStatus(classSettlement.getClassNo());
                            return AjaxResult.success("小票补打成功");
                        }
                    }

                    //初始化终端信息
                    m.init(stationDevice.getClientId(), stationDevice.getClientSecret());
                    //获取token
                    String refreshToken = m.getFreedomToken();
                    //存入redis
                    redisCache.setCacheObject("STATION:DEVICE:" + stationDevice.getClientId(),refreshToken,30, TimeUnit.DAYS);


                    printRes = m.print(stationDevice.getDeviceNo(), audio + ylyContent, random6.toString());

                    log.info("小票机返回值2{}",printRes);
                    org.json.JSONObject json = new org.json.JSONObject(printRes);
                    if("0".equals(json.getString("error"))){
                        //修改小票打印状态
                        classSettlementService.updateClassSettlementPrintStatus(classSettlement.getClassNo());
                        ajaxResult = AjaxResult.success("补打小票成功");
                    }else {
                        ajaxResult = AjaxResult.error("补打小票失败");
                    }

                    break;
                case FEIE:
                    String result  = FeiEPrinterUtil.printReceipt(stationDeviceManages.get(0).getDeviceNo(), content.toString());
                    org.json.JSONObject resJson = new org.json.JSONObject(result);
                    if("ok".equals(resJson.get("msg"))){
                        printRes = "补打小票成功";
                        ajaxResult = AjaxResult.success(printRes);
                        //修改小票打印状态
                        classSettlementService.updateClassSettlementPrintStatus(classSettlement.getClassNo());
                    }else {
                        printRes = "补打小票失败";
                        ajaxResult = AjaxResult.error(printRes);
                    }
                    break;
            }


            return ajaxResult;
        } catch (Exception e) {
            logger.error(">pushConsumeToUser", e);
            return AjaxResult.error("补打失败");
        }

    }

    private String padCountString(String input) {
        if(StringUtils.isEmpty(input)){
            return input;
        }
        int length = input.length();
        if (length >= 5) {
            return input;
        } else {
            StringBuilder paddedString = new StringBuilder(input);
            for (int i = 0; i < (5 - length); i++) {
                paddedString.append(" ");
            }
            return paddedString.toString();
        }
    }

    private String padCountOilNameString(String input) {
        if(StringUtils.isEmpty(input)){
            return input;
        }
        int length = input.length();
        if (length >= 4) {
            return input;
        } else {
            StringBuilder paddedString = new StringBuilder(input);
            for (int i = 0; i < (4 - length); i++) {
                paddedString.append(" ");
            }
            return paddedString.toString();
        }
    }

    public void getPushMessage(ClassSettlement classSettlement) {
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("stationId", classSettlement.getStationId());
        queryMap.put("classNo", classSettlement.getClassNo());

        //合计所有油品信息的集合
        List<ClassSettlement> sumOilList = classSettlementService.queryClassSettlementOil(queryMap);
        //合计班结信息，按照支付方式的集合
        List<ClassSettlement> sumPayTypeList = classSettlementService.queryClassSettlementPayType(queryMap);

        ClassSettlementCard classSettlementCard = new ClassSettlementCard();
        classSettlementCard.setClassNo(classSettlement.getClassNo());
        //合计班结信息，充值的信息集合
        List<ClassSettlementCard> sumCzList = classSettlementCardService.queryGroupByCardType(classSettlementCard);
        //合计  班结总计的信息集合
        //        List<ClassSettlement> sumClassList = classSettlementService.querySummaryByClassNo(queryMap);
        //加油员班结信息汇总
        List<ClassSettlement> oilPersonList = classSettlementService.selectClassSettlementSummaryUser(queryMap);
        //充值金额合计
        ClassSettlementCard classSettlementCardCz = classSettlementCardService.querySumCz(queryMap);

        //退款信息
        ClassSettlementCard form = new ClassSettlementCard();
        form.setClassNo(classSettlement.getClassNo());
        List<ClassSettlementCard> classSettlementCards = classSettlementCardService.selectClassSettlementCardList(form);

        CardClassSettDto settDto = countCardSett(classSettlementCards); //电子卡交易汇总数据
        Map<String, Object> params = new HashMap<String, Object>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (classSettlement.getClassStartTime() != null) {
            String classStartTime = dateFormat.format(classSettlement.getClassStartTime());
            params.put("createStartTime", classStartTime);
        }

        List<ClassSettlement> sumClassList = classSettlementService.querySummaryByClassNoAllData(queryMap,settDto);

        params.put("createEndTime", dateFormat.format(classSettlement.getClassEndTime()));
        params.put("stationId", classSettlement.getStationId());
        List<ClassSettlement> refundSummary = classSettlementService.getRefundSummary(settDto, params);
//        for (){
//
//        }
//        cjhyref
        //充值汇总统计
        List<ClassSettlementCard> transactionSummary = classSettlementService.getTransactionSummary(settDto, params);

        List<Map<String, Object>> oilPersonClass = new ArrayList<>();
        for (int i = 0; i < oilPersonList.size(); i++) {
            Map<String, Object> person1 = new HashMap<>();
            person1.put("personName", oilPersonList.get(i).getOilPersonnelName());
            if (classSettlement.getClassStartTime() == null) {
                person1.put("classStartTime", "首次");
            } else {
                person1.put("classStartTime", fmt.format(classSettlement.getClassStartTime()));
            }
            person1.put("classEndTime", fmt.format(classSettlement.getClassEndTime()));
            Map<String, Object> queryMap1 = new HashMap<>();
            queryMap1.put("stationId", classSettlement.getStationId());
            queryMap1.put("classNo", classSettlement.getClassNo());
            queryMap1.put("oilPersonnelId", oilPersonList.get(i).getOilPersonnelId());
            //合计所有油品信息的集合
            List<ClassSettlement> OilList = classSettlementService.queryClassSettlementOil(queryMap);
            person1.put("oilList", OilList);
            person1.put("orderCount", oilPersonList.get(i).getOrderCount());
            person1.put("receivableAmt", oilPersonList.get(i).getReceivableAmt());
            person1.put("discountAmt", oilPersonList.get(i).getDiscountAmt());
            person1.put("refundAmt", oilPersonList.get(i).getRefundAmt());
            person1.put("amt", oilPersonList.get(i).getAmt());
            person1.put("oilPersonnelName", oilPersonList.get(i).getOilPersonnelName());
            oilPersonClass.add(person1);
        }
        Map<String, Object> sumClassMap = new HashMap<>();
        sumClassMap.put("sumClassList", sumClassList);
        sumClassMap.put("sumOilList", sumOilList);
        sumClassMap.put("sumPayTypeList", sumPayTypeList);
        sumClassMap.put("sumCzList", sumCzList);
        sumClassMap.put("oilPersonClass", oilPersonClass);


        //员工汇总

        List<Map<String, Object>> listDetail4User = classSettlementService.selectClassSettlement4User4POSList(queryMap);


        this.feiePush(sumClassList, sumOilList, sumPayTypeList, sumCzList, oilPersonClass, classSettlementCardCz,classSettlement,refundSummary, listDetail4User, transactionSummary);
    }

    public AjaxResult getPushMessageRePrint(ClassSettlement classSettlement) {
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("stationId", classSettlement.getStationId());
        queryMap.put("classNo", classSettlement.getClassNo());
        log.info("queryMap{}",queryMap);
        //合计所有油品信息的集合
        List<ClassSettlement> sumOilList = classSettlementService.queryClassSettlementOil(queryMap);
        log.info("sumOilList{}",sumOilList);
        //合计班结信息，按照支付方式的集合
        List<ClassSettlement> sumPayTypeList = classSettlementService.queryClassSettlementPayType(queryMap);

        ClassSettlementCard classSettlementCard = new ClassSettlementCard();
        classSettlementCard.setClassNo(classSettlement.getClassNo());
        //合计班结信息，充值的信息集合
        List<ClassSettlementCard> sumCzList = classSettlementCardService.queryGroupByCardType(classSettlementCard);
        //合计  班结总计的信息集合
//        List<ClassSettlement> sumClassList = classSettlementService.querySummaryByClassNo(queryMap);

        //加油员班结信息汇总
        List<ClassSettlement> oilPersonList = classSettlementService.selectClassSettlementSummaryUser(queryMap);
        //充值金额合计
        ClassSettlementCard classSettlementCardCz = classSettlementCardService.querySumCz(queryMap);


        //退款信息
        ClassSettlementCard form = new ClassSettlementCard();
        form.setClassNo(classSettlement.getClassNo());
        List<ClassSettlementCard> classSettlementCards = classSettlementCardService.selectClassSettlementCardList(form);

        CardClassSettDto settDto = countCardSett(classSettlementCards); //电子卡交易汇总数据
        List<ClassSettlement> sumClassList = classSettlementService.querySummaryByClassNoAllData(queryMap,settDto);
        Map<String, Object> params = new HashMap<String, Object>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (classSettlement.getClassStartTime() != null) {
            String classStartTime = dateFormat.format(classSettlement.getClassStartTime());
            params.put("createStartTime", classStartTime);
        }

        params.put("createEndTime", dateFormat.format(classSettlement.getClassEndTime()));
        params.put("stationId", classSettlement.getStationId());
        List<ClassSettlement> refundSummary = classSettlementService.getRefundSummary(settDto, params);
        //充值汇总统计
        List<ClassSettlementCard> transactionSummary = classSettlementService.getTransactionSummary(settDto, params);


        List<Map<String, Object>> oilPersonClass = new ArrayList<>();
        for (int i = 0; i < oilPersonList.size(); i++) {
            Map<String, Object> person1 = new HashMap<>();
            person1.put("personName", oilPersonList.get(i).getOilPersonnelName());
            if (classSettlement.getClassStartTime() == null) {
                person1.put("classStartTime", "首次");
            } else {
                person1.put("classStartTime", fmt.format(classSettlement.getClassStartTime()));
            }
            person1.put("classEndTime", fmt.format(classSettlement.getClassEndTime()));
            Map<String, Object> queryMap1 = new HashMap<>();
            queryMap1.put("stationId", classSettlement.getStationId());
            queryMap1.put("classNo", classSettlement.getClassNo());
            queryMap1.put("oilPersonnelId", oilPersonList.get(i).getOilPersonnelId());
            //合计所有油品信息的集合
            List<ClassSettlement> OilList = classSettlementService.queryClassSettlementOil(queryMap);
            person1.put("oilList", OilList);
            person1.put("orderCount", oilPersonList.get(i).getOrderCount());
            person1.put("receivableAmt", oilPersonList.get(i).getReceivableAmt());
            person1.put("discountAmt", oilPersonList.get(i).getDiscountAmt());
            person1.put("refundAmt", oilPersonList.get(i).getRefundAmt());
            person1.put("amt", oilPersonList.get(i).getAmt());
            person1.put("oilPersonnelName", oilPersonList.get(i).getOilPersonnelName());
            oilPersonClass.add(person1);
        }
        Map<String, Object> sumClassMap = new HashMap<>();
        sumClassMap.put("sumClassList", sumClassList);
        sumClassMap.put("sumOilList", sumOilList);
        sumClassMap.put("sumPayTypeList", sumPayTypeList);
        sumClassMap.put("sumCzList", sumCzList);
        sumClassMap.put("oilPersonClass", oilPersonClass);

        List<Map<String, Object>> listDetail4User = classSettlementService.selectClassSettlement4User4POSList(queryMap);

        //充值汇总
        List<Map<String, Object>> queryGroupByPayType = classSettlementService.queryGroupByPayType(queryMap);
        List<ClassSettlementCard> queryGroupByRecharge = classSettlementService.queryGroupByRecharge(queryGroupByPayType,settDto);
        return this.feiePushRePrint(sumClassList, sumOilList, sumPayTypeList, sumCzList, oilPersonClass, classSettlementCardCz,classSettlement,refundSummary, listDetail4User, transactionSummary, queryGroupByRecharge);

    }

    @ApiOperation(value = "自动班结设置")
    @PostMapping("/setAutomaticClass")
    @ResponseBody
    public AjaxResult setAutomaticClass( @RequestBody AutomaticClassDto classDto) throws Exception {
        log.info("setAutomaticClass---入参：{}",classDto);
        if (0 == classDto.getIsAuto()){
            automaticClassService.deleteAutomaticClass(classDto);
            return AjaxResult.success();
        }
        for (AutomaticClassInfo automaticClassInfo : classDto.getAutomaticClassInfos()) {
            if (null == automaticClassInfo.getStationId()){
                throw new CustomException("油站id不能为空");
            }
            if (automaticClassInfo.getKnotTimes().isEmpty()){
                throw new CustomException("班结时间不能为空");
            }
        }
        int i = automaticClassService.insertAutomaticClass(classDto);
        if (i == 1){
            return AjaxResult.success();
        }

        return AjaxResult.error("自动班结设置失败");
    }

    @ApiOperation(value = "获取自动班结")
    @GetMapping("/getAutomaticClass")
    @ResponseBody
    public AjaxResult getAutomaticClass(Long id){

        AutomaticClassDto automaticClass = automaticClassService.getAutomaticClass(id);

        return AjaxResult.success(automaticClass);
    }
    @GetMapping("/getEnterpriseStationList")
    @ApiOperation(value = "获取班结油站信息列表", notes = "获取班结油站信息列表")
    public  List<Station> getEnterpriseStationList(Station station)
    {
        station.setDeleteStatus("0");
//        station.setStatus("1");
        LoginUser current=SecurityUtils.getLoginUser();
        List<Station> stations = new ArrayList<>();
        SysUser user = current.getUser();
        if(SecurityUtils.isPartner()){
            EnterpriseAndStationVo itemIds = stationService.getItemIds(current.getUser());
            List<Long> enterpriseIds = itemIds.getEnterpriseIds();
            if (enterpriseIds != null && enterpriseIds.size()>0) {
                station.setEnterpriseIdListForAuthor(enterpriseIds);
            } else {
                throw new CustomException(UserConstants.NO_ENTERPRISE);
            }
        }

        if(current.getUser().getEnterpriseId()==null){
            stations = stationService.selectStationList(station);
        }else{
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            stations = stationService.selectStationList(station);
            for (Station station1 : stations) {
                if (station1.getStatus().equals("0")){
                    station1.setStationName(station1.getStationName()+"(已停用)");
                }
            }
        }
        return stations;
    }

}
